在Go中,如何在结构中带有指向数组的指针?

I would have expected this code to work:

package main

type Item struct {
  Key string
  Value string
}

type Blah struct {
  Values []Item
}

func main() {
  var list = [...]Item {
    Item {
      Key : "Hello1",
      Value : "World1",
    },
    Item {
      Key : "Hello1",
      Value : "World1",
    },
  }

  _ = Blah {
    Values : &list,
  }
}

I thought this would be the correct way of doing this; Values is a slice, list is an array. &list should be a slice, which is assignable to Item[], right?

...but instead, it errors with the message:

cannot use &list (type *[2]Item) as type []Item in assignment

In C, you'd write:

struct Item {
  char *key;
  char *value;
};

struct Blah {
   struct Item *values;
};

How do you do that in Go?

I saw this question: Using a pointer to array

...but either the answers are for a previous version of Go, or they're just plain wrong. :/

A slice is not simply a pointer to an array, it has an internal representation which contains its length and capacity.

If you want to get a slice from list you can do:

_ = Blah {
    Values : list[:],
}

Go is, fortunately, not so verbose as it might seem from the OP. This works:

package main

type Item struct {
        Key, Value string
}

type Blah struct {
        Values []Item
}

func main() {
        list := []Item{
                {"Hello1", "World1"},
                {"Hello2", "World2"},
        }

        _ = Blah{list[:]}
}

(Also here)

PS: Let me suggest to not write C in Go.

When you are starting out with Go ignore arrays completely and just use slices is my advice. Arrays are rarely used and cause Go beginners a lot of trouble. If you have a slice then you don't need a pointer to it since it is a reference type.

Here is your example with a slice and no pointers which is much more idiomatic.

package main

type Item struct {
    Key   string
    Value string
}

type Blah struct {
    Values []Item
}

func main() {
    var list = []Item{
        Item{
            Key:   "Hello1",
            Value: "World1",
        },
        Item{
            Key:   "Hello1",
            Value: "World1",
        },
    }

    _ = Blah{
        Values: list,
    }
}