簡體   English   中英

在struct golang中打印一個struct

[英]print a struct within a struct golang

我想在結構內打印某個項目,該結構在結構內。 例:
假裝我已經構造了一個藍圖結構,並且正在制作一個新的藍圖結構
假設我有一個myshapes結構,其中包含標題,圓形和正方形的數量

car := blueprints{
dots: 5,
lines: 25,
shapes: []myshapes{
    myshapes{
        title:"car #1",
        circles:5,
        squares:7,
    },
    myshapes{
        title:"car #2",
        circles:2,
        squares:14,
    },
}

如何打印:

title:"car #1"
circles:5
squares:7
title:"car #2"
circles:2
squares:14

以下示例顯示了如何打印結構的特定字段值:

type child struct {
    name string
    age int
}

type parent struct {
    name string
    age int
    children child
}

func main() {
    family := parent{
        name: "John",
        age: 40,
        children: child{
            name: "Johnny",
            age: 10,
        },
    }

    fmt.Println(family.children.name); // Prints "Johnny"
}

上面的代碼將顯示“ Johnny”,這是父結構中一個結構的值。 代碼中並沒有太大的意義,但是,因為該領域是children ,但始終只能夠是一個孩子作為它的值。

讓我們利用切片。 既然我們知道如何打印特定值,那么您需要做的就是遍歷一個切片並以與上面相同的方式打印。

我們可以這樣做:

type child struct {
    name string
    age int
}

type parent struct {
    name string
    age int
    children []child
}

func main() {
    family := parent{
        name: "John",
        age: 40,
        children: []child{
            child{
                name: "Johnny",
                age: 10,
            },
            child{
                name: "Jenna",
                age: 7,
            },
        },
    }

    for _, child := range family.children {
        fmt.Println(child.name);
    }
}

上面的示例將引用“ Johnny”和“ Jenna”。

您可以使用與我上面在自己的代碼中顯示的模式類似的模式來遍歷您的結構並打印出您心中想要的任何值:)


請記住 ,有很多方法可以遍歷事物。 例如,下面的所有循環將從上面的示例中打印“ Johnny”和“ Jenna”。

for _, child:= range family.children{ // Prints "Jonny" and "Jenna"
    fmt.Println(child.name); 
}

for i, _ := range family.children{ // Prints "Jonny" and "Jenna"
    fmt.Println(family.children[i].name);
}

for i := 0; i < len(family.children); i++ { // Prints "Jonny" and "Jenna"
    fmt.Println(family.children[i].name);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM