英文:
Set array value into structure in golang
问题
结构体TopicModels
中的Topics
字段的类型是[]string
,表示一个字符串切片。你想要将值设置到这个结构体中,可以按照以下方式进行操作:
var topics []string
topics = append(topics, "Sport Nice")
topics = append(topics, "Nice Sport")
return &TopicModels{Topics: topics}, nil
这样就可以正确地将值设置到TopicModels
结构体中了。
英文:
The structure is
type TopicModels struct {
Topics []string
}
And I want to set the value into this structure like following approach
var topics [2]string
topics[0] = "Sport Nice"
topics[1] = "Nice Sport"
return &TopicModels{Topics: topics}, nil
However, it tells me that
cannot use topics (type [2]string) as type []string in field value
How can I change the code to make it correct?
答案1
得分: 3
错误消息显示,Topics
字段的类型是[]string
(一个任意长度的字符串切片),而topics
变量的类型是[2]string
(一个长度为2的字符串数组)。这些类型不相同,所以你会得到错误。
你可以有两种解决方法:
-
将
topics
变量改为切片类型:topics := make([]string, 2) topics[0] = "Sport Nice" ...
-
使用slice表达式来创建表示你的数组的切片:
... return &TopicModels{Topics: topics[:]}, nil
英文:
As the error message says, the Topics
field has type []string
(an arbitrary length slice of strings), and the topics
variable has type [2]string
(an string array of length 2). These are not the same type, so you get the error.
There are two ways you could go about solving this:
-
make
topics
a slice:topics = make([]string, 2) topics[0] = "Sport Nice" ...
-
Use a slice expression to create a slice representing your array:
... return &TopicModels{Topics: topics[:]}, nil
答案2
得分: 1
你也可以使用数组字面量
来实现,方法如下:
topics := [2]string{"Sport Nice", "Nice Sport"}
return &TopicModels{Topics: topics}, nil
这里有一篇关于数组和切片的不错的博客文章:Go Slices: usage and internals
编辑:
我忘了提到你需要修改结构体:
type TopicModels struct {
Topics [2]string
}
英文:
You can also use an array literal
by doing this...
topics := [2]string{"Sport Nice","Nice Sport"}
return &TopicModels{Topics: topics}, nil
Here is a nice blog entry about array's and slices... http://blog.golang.org/go-slices-usage-and-internals
EDIT
forgot to mention you need to change the struct
type TopicModels struct {
Topics [2]string
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论