Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

go - cannot use address (type string) as type AccountAddress in assignment

I'm facing an issue while assignment of a string with a type of type AccountAddress [16]uint8.

type AccountAddress [16]uint8

address := c.Param("adress")
var account AccountAddress
account = address
Error cannot use address (type string) as type AccountAddress in assignment

Tried:

 var account diemtypes.AccountAddress
 account = []uint8(address)
Error cannot use ([]uint8)(address) (type []uint8) as type diemtypes.AccountAddress in assignment

Can anyone please help me in this.

question from:https://stackoverflow.com/questions/65840381/cannot-use-address-type-string-as-type-accountaddress-in-assignment

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here you are confusing many basic things thing. Let me clear them on by one

  1. In golang custom types are treated as separate types even both are defined with the same built-in type

For example

    type StringType1 string 
    type StringType2 string
    
    var name1 StringType1="Umar"
    var name2 StringType2="Hayat"
    
    fmt.Println("StringType1 : ", name1)
    fmt.Println("StringType2 : ", name2)

The output of the above code is https://play.golang.org/p/QDcaM1IolbJ

StringType1 :  Umar
StringType2 :  Hayat

Here we have two custom types StringType1 and StringType2 both are defined by string`. But we can not assign a variable of these two types to each other directly until we convert them to the required type e.g

    name1=name2

Output

cannot use name2 (type StringType2) as type StringType1 in assignment

Similar is the case with your code. You are converting a string to a custom type without applying conversion.

  1. Second you are trying to convert a string to a byte array of fixed length 15 and type uint8. This can be done as mentioned by @Cerise Limon
copy(account[:], c.Param("adress"))

But keep one thing here in mind you are copying string to unit8 type so you should not expect characters in account instead it will be ASCI values of that string character. I hope it will clear all your miss conceptions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...