如何构造切片结构的对象?

package main


import (

    "fmt"

)

type demo []struct {

    Text string

    Type string

}

func main() {

    

    d := demo{

        Text: "Hello",

        Type: "string",

    }

    

}


在这段代码中,我在声明demostruct 对象时遇到错误:


./prog.go:11:3: undefined: Text

./prog.go:11:9: cannot use "Hello" (untyped string constant) as struct{Text string; 在数组或切片文字中键入 string} 值

./prog.go:12:3: undefined: Type

./prog.go:12:9: cannot use "string" (untyped string constant) as struct{Text string; 在数组或切片文字中键入 string} 值


很明显,因为它不是普通的结构声明,所以请帮助我如何构造结构对象demo?


侃侃尔雅
浏览 71回答 1
1回答

阿晨1998

由于您声明demo为匿名结构的切片,因此您必须使用demo{}来构造切片并{Text: "Hello", Type: "string"}构造项目。func main() {    d := demo{{        Text: "Hello",        Type: "Anon",    }}    fmt.Println(d)    // [{Hello Anon}]}作为一个切片,你也make可以,但是附加项目需要复制匿名结构的定义:func main()    d1 := make(demo, 0)    d1 = append(d1, struct {        Text string        Type string    }{"Hello", "Append"})    fmt.Println(d1)    // [{Hello Append}]}尽管它可以编译,但它并不常见。只需定义命名的结构类型,然后d作为其中的一部分。语法几乎相同,但简单明了:// just defined struct typetype demo struct {    Text string    Type string}func main() {        d2 := []demo{{        Text: "Hello",        Type: "Slice",    }}    fmt.Println(d2)    // [{Hello Slice}]}游乐场:https ://go.dev/play/p/4kSXqYKEhst
打开App,查看更多内容
随时随地看视频慕课网APP