package main
import (
"fmt"
)
type demo []struct {
Text string
Type string
}
func main() {
d := demo{
Text: "Hello",
Type: "string",
}
}
在這段代碼中,我在宣告演示結構的物件時遇到錯誤,很明顯,因為它不是正常的結構宣告,所以請幫助我如何制作演示結構的物件?
uj5u.com熱心網友回復:
由于您宣告demo為匿名結構的切片,因此您必須使用demo{}來構造切片和{Text: "Hello", Type: "string"}構造專案。
func main() {
d := demo{{
Text: "Hello",
Type: "string",
}}
fmt.Println(d)
// [{Hello string}]
}
然而,盡管它可以編譯,但它并不常見。只需宣告您的結構型別,然后d作為其中的一部分。語法幾乎相同,但更直接:
// just defined struct type
type demo struct {
Text string
Type string
}
func main() {
d := []demo{{
Text: "Hello",
Type: "string",
}}
fmt.Println(d)
// [{Hello string}]
}
游樂場:https : //go.dev/play/p/mQ7s4TiWCIC
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/373107.html
標籤:走
