简体   繁体   中英

Missing type in composite literal while working with string[][] in map in golang

This is my code:

package main

import (
    "fmt"
)
type person struct {
        //name  [][]string{};
        name [][]string
    }  

func main() {
var people = map[string]*person{}

people["first person"] = &person{name:{{"My name","30"}}}
    fmt.Println(people["first person"])
}

I have an error:

missing type in composite literal

I want output as [[My name,30]]

Could someone help me?

Here is working example. You must declare type of composed literal before using.

package main

import (
    "fmt"
)

type person struct {
    //name  [][]string{};
    name [][]string
}

func main() {
    var people = map[string]*person{}

    people["first person"] = &person{name: [][]string{{"John", "30"}}}
    fmt.Println(people["first person"])
}

You are missing type while creating an instance pointer and initializing it, it should be:

&person{name: [][]string{{"My name, 30"}}}

Below is the working example:

package main

import (
    "fmt"
)

type person struct {
    name [][]string
}

func main() {
    var people = map[string]*person{}
    people["first person"] = &person{name: [][]string{{"My name, 30"}}}
    fmt.Println(people["first person"].name)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM