首页 > 解决方案 > 不能在分配中使用地址(类型字符串)作为 AccountAddress 类型

问题描述

我在分配类型为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

试过:

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

任何人都可以在这方面帮助我。

标签: go

解决方案


在这里,您混淆了许多基本的东西。让我清除它们一个

  1. 在 golang 中,自定义类型被视为单独的类型,即使两者都使用相同的内置类型定义

例如

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

上述代码的输出是https://play.golang.org/p/QDcaM1IolbJ

StringType1 :  Umar
StringType2 :  Hayat

这里我们有两个自定义类型StringType1StringType2 both are defined by 字符串。但是我们不能直接将这两种类型的变量相互分配,直到我们将它们转换为所需的类型,例如

    name1=name2

输出

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

您的代码也是如此。您正在将 a 转换string为自定义类型而不应用转换。

  1. 其次,您尝试将 a 转换string为固定长度 15 的字节数组并键入uint8。这可以按照@Cerise Limon 所述完成
copy(account[:], c.Param("adress"))

但是请记住一件事,您正在复制stringunit8键入,因此您不应该期望字符,account而是该字符串字符的 ASCI 值。我希望它能清除你所有的错觉。


推荐阅读