Set array value into structure in golang

huangapple go评论83阅读模式
英文:

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的字符串数组)。这些类型不相同,所以你会得到错误。

你可以有两种解决方法:

  1. topics变量改为切片类型:

     topics := make([]string, 2)
     topics[0] = "Sport Nice"
     ...
    
  2. 使用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:

  1. make topics a slice:

     topics = make([]string, 2)
     topics[0] = "Sport Nice"
     ...
    
  2. 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
}

huangapple
  • 本文由 发表于 2015年6月29日 08:19:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/31106153.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定