在struct golang中打印一个struct

时间:2016-02-19 02:45:30

标签: go struct

我想在结构中打印某个项目,即在结构体内。例如:
假装我已经制作了一个蓝图结构,并正在制作一个新的结构
假装我有一个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

1 个答案:

答案 0 :(得分:1)

下面的示例显示了如何打印结构的特定字段值:

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);
    }
}

上面的例子将是pront" Johnny"和"珍娜"。

您可以在我们自己的代码中使用与上面显示的类似的模式来遍历您的结构并打印您心中所需的任何值:)

请记住,有很多方法可以循环使用。例如,以下所有循环都会打印" Johnny"和"珍娜"从上面的例子中可以看出。

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);
}
相关问题