iT邦幫忙

4

蠻可愛的golang #26 - 結構 Struct

跟C一樣,golang有結構,來看看簡單的宣告,儲值及取值的範例.

// hello30
package main

import (
	"fmt"
)

type struct1 struct {
	str string
	i1  int
	f1  float32
}

func main() {
	ns := new(struct1)
	ns.i1 = 5
	ns.f1 = 99.99
	ns.str = "struct1"
	fmt.Printf("%d\n", ns.i1)
	fmt.Printf("%f\n", ns.f1)
	fmt.Printf("%s\n", ns.str)
	fmt.Printf("%v\n", ns)
}

執行結果:

$ ./hello30 
5
99.989998
struct1
&{struct1 5 99.99}

用 type 方式宣告,用內建函數new()來建立一個struct.
最後用%v參數來列印,會依照宣告順序,將struct內容印出來,
%v是golang fmt printf 很好用的參數.


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言