go - 不能在分配中使用地址(类型字符串)作为 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
任何人都可以在这方面帮助我。
解决方案
在这里,您混淆了许多基本的东西。让我清除它们一个
- 在 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
这里我们有两个自定义类型StringType1
和StringType2 both are defined by
字符串。但是我们不能直接将这两种类型的变量相互分配,直到我们将它们转换为所需的类型,例如
name1=name2
输出
cannot use name2 (type StringType2) as type StringType1 in assignment
您的代码也是如此。您正在将 a 转换string
为自定义类型而不应用转换。
- 其次,您尝试将 a 转换
string
为固定长度 15 的字节数组并键入uint8
。这可以按照@Cerise Limon 所述完成
copy(account[:], c.Param("adress"))
但是请记住一件事,您正在复制string
以unit8
键入,因此您不应该期望字符,account
而是该字符串字符的 ASCI 值。我希望它能清除你所有的错觉。
推荐阅读
- ios - 如何在 iOS 中使用 React Native 保存下载的文件并在文件应用程序中查看?
- lotus-domino - 与 NAMELookup2 一起挂起的 Domino 邮箱工具
- javascript - 如何在单击 javascript 中的按钮时使用通用数据填充表单?
- elasticsearch - 如何使用 NEST 搜索到默认索引?
- flutter - 如何将文本与底部对齐
- google-cloud-dataflow - 运行数据流时出现问题
- c# - C# 如何使用 Caliburn.Micro 将 WPF 滚动条值绑定到 ViewModel
- asp.net - 如何从项目/解决方案中完全删除包?
- ruby - 如何在 Chef 14 中执行 dpkg-query?
- .net - .net MS Excel 互操作插件