英文:
Does Go have an iterator datatype?
问题
如何编写能够像C++中的map迭代器一样工作的Go代码?
type MyStruct struct {
v1 string
v2 string
}
myMap := make(map[string]MyStruct)
value, ok := myMap["key"]
if ok {
value.v1 = something
value.v2 = something
myMap["key"] = value
}
英文:
How do I write Go code that can do something like a map iterator in C++?
typedef std::map<std::string, MyStruct> MyMap;
MyMap::iterator it = myMap.find("key");
if(it!=myMap.end()) {
it->v1 = something;
it->v2 = something;
}
答案1
得分: 8
在Go语言中,使用range子句遍历map非常简单。
myMap := map[string]int {"one":1, "two":2}
for key, value := range myMap {
// 做一些操作。
fmt.Println(key, value)
}
可能会打印出
one 1
two 2
请注意,遍历map时的顺序是不确定的,因为它是由哈希表而不是树支持的。
Go语言的语言规范描述了range子句返回的内容,您可以在effective go页面上看到更多示例。
英文:
In go, it is pretty easy to iterate over a map using the range clause.
myMap := map[string]int {"one":1, "two":2}
for key, value := range myMap {
// Do something.
fmt.Println(key, value)
}
Could print
one 1
two 2
Note that you iterate in an undefined order over a map, as it is backed by a hash table rather than a tree.
The go language spec describes what the range clause returns, and you can see the effective go page for some more examples.
答案2
得分: 2
如果你只是想在一个映射中找到一个键,那么请使用以下代码:
package main
import (
"fmt"
)
type Point struct {
x, y int
}
func main() {
points := make(map[string]*Point)
p := &Point{1, 1}
points["one"] = p
if p1, found := points["one"]; found {
p1.x = 100
}
fmt.Println(p)
}
英文:
If you're just trying to find a key in a map, then use the following:
package main
import (
"fmt"
)
type Point struct {
x, y int
}
func main() {
points := make(map[string]*Point)
p := &Point{1, 1}
points["one"] = p
if p1, found := points["one"]; found {
p1.x = 100
}
fmt.Println(p)
}
答案3
得分: 0
例如,
package main
import "fmt"
type MyStruct struct {
v1 string
v2 int
}
type MyMap map[string]MyStruct
func main() {
m := MyMap{
"unum": MyStruct{"I", 1},
"duo": MyStruct{"II", 2},
}
fmt.Println("before:")
for k, v := range m {
fmt.Println(k, v)
}
var k string
k = "unum"
if v, ok := m[k]; ok {
v.v1 = "one"
v.v2 = 1
m[k] = v
}
k = "tria"
if v, ok := m[k]; ok {
v.v1 = "III"
v.v2 = 3
m[k] = v
}
fmt.Println("after:")
for k, v := range m {
fmt.Println(k, v)
}
}
输出:
before:
unum {I 1}
duo {II 2}
after:
unum {one 1}
duo {II 2}
英文:
For example,
package main
import "fmt"
type MyStruct struct {
v1 string
v2 int
}
type MyMap map[string]MyStruct
func main() {
m := MyMap{
"unum": MyStruct{"I", 1},
"duo": MyStruct{"II", 2},
}
fmt.Println("before:")
for k, v := range m {
fmt.Println(k, v)
}
var k string
k = "unum"
if v, ok := m[k]; ok {
v.v1 = "one"
v.v2 = 1
m[k] = v
}
k = "tria"
if v, ok := m[k]; ok {
v.v1 = "III"
v.v2 = 3
m[k] = v
}
fmt.Println("after:")
for k, v := range m {
fmt.Println(k, v)
}
}
Output:
before:
unum {I 1}
duo {II 2}
after:
unum {one 1}
duo {II 2}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论