2015-06-29 00:19
浏览 40


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?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doufang7385 2015-06-29 00:39

    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
    解决 无用
    打赏 举报

相关推荐 更多相似问题