1. 程式人生 > 實用技巧 >Go基礎及語法(四)

Go基礎及語法(四)

目錄

結構體

package main

import "fmt"

//定義結構體
type person struct {
	name string
	age  int
}

func main() {
	p1 := person{name: "a", age: 18} //初始化結構體
	fmt.Println(p1) //{a 18}
}

匿名結構體

package main

import "fmt"

func main() {
	//匿名結構體
	p2 := struct {
		name string
		age  int
	}{name: "b", age: 20}
	fmt.Println(p2.name, p2.age) //b 20
}

建構函式

package main

import "fmt"

type person struct {
	name string
	age  int
}

//建構函式
func newPerson(s string, i int) (p person) {
	p = person{
		name: s,
		age:  i,
	}
	return p
}

func main() {
	p3 := newPerson("c", 22) //初始化結構體
	fmt.Println(p3)          //{c 22}
}

方法和接收者

package main

import "fmt"

type person struct {
	name string
	age  int
}

func newPerson(s string, i int) (p person) {
	p = person{
		name: s,
		age:  i,
	}
	return p
}

/*
構造方法
func (接收者 型別) 方法名(){
	方法主體
}
 */
func (p person) method() {
	fmt.Println("person's method") //person's method
}

func main() {
	p4 := newPerson("d", 24) //初始化結構體
	p4.method() //呼叫方法
}

結構體的值

在Go語言中,函式之間引數的傳遞都是經過拷貝的,如果想在方法上修改結構體的值,需傳入指標

package main

import "fmt"

type person struct {
	name string
	age  int
}

func newPerson(s string, i int) (p person) {
	p = person{
		name: s,
		age:  i,
	}
	return p
}

func (p person) method1() {
	p.age++
}

//*接收傳遞引數的指標
func (p *person) method2() {
	p.age++
}

func main() {
	p5 := newPerson("d", 24)
	p5.method1()
	fmt.Println(p5.age) //24
	p5.method2()
	fmt.Println(p5.age) //25
}

結構體的巢狀和匿名欄位

package main

import "fmt"

type person struct {
	name string
	age  int
}

type school struct {
	class  string
	person //結構體的匿名欄位
}

func main() {
	s := school{
		class: "A",
		person: person{
			name: "a",
			age:  18,
		},
	}
	fmt.Println(s) //{A {a 18}}
}

JSON序列化與反序列化

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

type school2 struct {
	Class  string
	Person Person
}

func main() {
	s := school2{
		Class: "A",
		Person: Person{
			Name: "a",
			Age:  18,
		},
	}
	k, v := json.Marshal(s) //JSON序列化
	if v != nil {
		fmt.Println("JSON反有誤")
	}
	fmt.Println(string(k)) //{"Class":"A","Person":{"Name":"a","Age":18}}
}

匿名結構體

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

type school struct {
	Class  string
	Person
}

func main() {
	s := school{
		Class: "A",
		Person: Person{
			Name: "a",
			Age:  18,
		},
	}
	k, v := json.Marshal(s) //序列化
	if v != nil {
		fmt.Println("JSON反有誤")
	}
	fmt.Println(string(k)) //{"Class":"A","Name":"a","Age":18}
	var s2 school
	json.Unmarshal([]byte(string(k)), &s2) //反序列化
	fmt.Println(s2) //{A {a 18}}
}