duanche4578 2015-06-29 00:19
浏览 41
已采纳

在golang中将数组值设置为结构

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
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作