如何修改 Go Map 值中的结构体字段?
寻址映射值
在 Go 中,尝试直接修改映射值中的结构体字段,如下例所示,将会导致编译错误:
import ( "fmt" ) type pair struct { a float64 b float64 } func main() { // Create a map where values are of the "pair" type. dictionary := make(map[string]pair) // Add an element to the map. dictionary["xxoo"] = pair{5.0, 2.0} fmt.Println(dictionary["xxoo"]) // Output: {5 2} // Attempt to modify a field within the map value. dictionary["xxoo"].b = 5.0 // Error: cannot assign to dictionary["xxoo"].b }
登录后复制
遇到此错误消息是因为映射值不可寻址。可寻址性是Go中的一个基本概念,它指的是定位变量内存地址的能力。无法间接修改不可寻址值,因为尝试访问不可寻址值的结构体字段会导致编译错误。
要解决此问题,主要有两种方法:
使用指针值
一种方法是使用指针值作为映射值。这种间接寻址使得值可寻址,从而允许字段修改。下面是一个示例:
import ( "fmt" ) type pair struct { a float64 b float64 } func main() { // Create a map where values are pointers to "pair" structs. dictionary := make(map[string]*pair) // Add an element to the map. dictionary["xxoo"] = &pair{5.0, 2.0} fmt.Println(dictionary["xxoo"]) // Output: &{5 2} // Modify a field within the pointed-to struct. dictionary["xxoo"].b = 5.0 fmt.Println(dictionary["xxoo"].b) // Output: 5 }
登录后复制
值复制或替换
或者,您可以通过复制值或完全替换它来处理不可寻址的值。以下是两个示例:
// Value Copying dictionary["xxoo"] = pair{5.0, 5.0}
登录后复制
// Value Replacement p := dictionary["xxoo"] p.b = 5.0 dictionary["xxoo"] = p
登录后复制
这两种方法都允许您修改映射中的“pair”结构。
以上是如何修改 Go Map 值中的结构体字段?的详细内容。更多信息请关注PHP中文网其他相关文章!
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前
By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
击败分裂小说需要多长时间?
3 周前
By DDD
R.E.P.O.保存文件位置:在哪里以及如何保护它?
3 周前
By DDD

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)