在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?

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
    

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
}