英文:
How i can get a value that is inside a map, inside other map?
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我是golang的新手,我遇到了这个问题。
package main
import "fmt"
func main() {
Problem := map[string]interface{}{
"Alan": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "28",
},
},
"Sophia": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "18",
},
},
}
Ages := []string{}
for key, value := range Problem {
fmt.Println(key)
fmt.Println(value)
Ages = value["Age"]
}
}
我想要使用"Age"的值做一些事情,我该如何做到这一点?
英文:
I'm newbie in golang and I have this problem.
package main
import "fmt"
func main() {
Problem := map[string]interface{}{
"Alan": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "28",
},
},
"Sophia": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "18",
},
},
}
Ages := []string{}
for key, value := range Problem {
fmt.Println(key)
fmt.Println(value)
Ages = value["Age"]
}
}
I want to use the valor of "Age" for something, how I can do this ?
答案1
得分: 0
interface{} 类型中的值可以是任何类型的值。在访问之前,使用 类型断言 来确保值的类型对于操作是有效的:
package main
import "fmt"
func main() {
Problem := map[string]interface{}{
"Alan": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "28",
},
},
"Sophia": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "18",
},
},
}
Ages := []string{}
for key, value := range Problem {
fmt.Println(key)
fmt.Println(value)
a, ok := value.(map[string]interface{})["Particulars"].(map[string]interface{})["Age"].(string)
if ok {
Ages = append(Ages, a)
}
}
fmt.Println(Ages)
}
英文:
A value in interface{} type can be any type of value. Use a type assertion to ensure the value type is valid for the operation before accessing it:
package main
import "fmt"
func main() {
Problem := map[string]interface{}{
"Alan": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "28",
},
},
"Sophia": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "18",
},
},
}
Ages := []string{}
for key, value := range Problem {
fmt.Println(key)
fmt.Println(value)
a, ok := value.(map[string]interface{})["Particulars"].(map[string]interface{})["Age"].(string)
if ok {
Ages = append(Ages, a)
}
}
fmt.Println(Ages)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论