Golang program that uses slice of structs, pointer types

作者: admin 分类: golang 发布时间: 2018-05-15 16:59 ė 6 没有评论
 package main

import "fmt"

type Location struct {
    x, y  int
    valid bool
}

func main() {
    // Create empty slice of struct pointers.
    places := []*Location{}

    // Create struct and append it to the slice.
    loc := new(Location)
    loc.x = 10
    loc.y = 20
    loc.valid = true

    places = append(places, loc)

    // Create another struct.
    loc = new(Location)
    loc.x = 5
    loc.y = 8
    loc.valid = true

    places = append(places, loc)

    // Loop over all indexes in the slice.
    // ... Print all struct data.
    for i := range(places) {
        place := places[i]
        fmt.Println("Location:", place)
    }
}

Output

Location: &{10 20 true}
Location: &{5 8 true}

本文出自 小Q,转载时请注明出处及相应链接。

本文永久链接: http://www.linuxqq.com/archives/1851.html

0
更多
Ɣ回顶部