【Go 基础学习 二】结构体 构造方法

Go 结构体

由于go没有class类, 很多语法类似C,继承使用了C的结构体struct

但是我看到go结构体里面,一般都是定义变量属性,没看到定义方法的,
那么如何实现构造方法了?

实现构造方法

在其他语言里面,一般实例化对象,都有会构造方法,Go里面一般是这样使用,间接实现构造方法,返回一个结构体对象。


package main

import (
	"fmt"
)

// 在定义一个结构体
type Mouse struct {
	name string
	color string
	sex bool
}

// 模拟构造方法 方法名随意
func NewMouse(name string, color string, sex bool) (m Mouse) {
	// 返回结构体对象 间接实现构造方法
	return Mouse{
		name:name,
		color: color,
		sex: sex,
	}
}

func main() {
	// 构造方法实例化
	Tuffy := NewMouse("Tuffy", "grey", true)
	fmt.Println(Tuffy)
}

结构体

package main

import (
	"fmt"
)

// 声明一个结构体
type Cat struct {
	name   string
	color  string
	sex    bool
	couple Mouse // 这里赋值为 另一个结构体, 如果和结构体名一样 可以省略一个
}

// 结构体挂载方法 使用指针 避免内存拷贝
func (c *Cat) CaptureMouse(name string) (res bool) {
	if c.name == name {
		fmt.Println("名字为Tom,能捉到老鼠")
		// 由于使用了指针, 可以改变结构体的值
		c.name = "old tom "
		return true
	} else {
		fmt.Println("名字不为Tom, 捉不到老鼠")
		return false
	}
}

// 在定义一个结构体
type Mouse struct {
	name string
	color string
	sex bool
}

// 结构体挂载方法 不使用指针 实例的成员会进行值复制
func (m Mouse) Eat(stuff string) (res bool) {
	if stuff == "奶酪" {
		fmt.Println(m.name, "喜欢吃", stuff)
		// 不能改变外部结构体的值
		m.name = "old jerry"
		return true
	} else {
		fmt.Println(m.name, "不喜欢吃", stuff)
		return false
	}
}

func main() {
	// 实例化结构体
	Tom := Cat{
		name:  "Tom",
		color: "white",
		sex:   true,
		couple: Mouse{
			name: "Jerry",
		},
	}

	// 调用方法
	res := Tom.CaptureMouse("Tom")
	fmt.Println(res)
	fmt.Println(Tom)
	// 通过子类属性调用子类的方法(我自己取的名字)
	Tom.couple.Eat("糖")
	Tom.couple.Eat("奶酪")
}

结构体的嵌套

package demo_test

import (
	"testing"
)

type Foo struct {
	Allen string
	Levy string
}

// Foo 指定类型  Spoke 与 Allen Levy 变量 不在同一层
type Bar struct {
	Spoke int
	Foo Foo
}

// 相当于继承 Foo   Zek 和 Allen Levy 变量在同一层
type Titan struct {
	Zek string
	Foo
}



func TestA(t *testing.T) {
	b := Bar{1, Foo{"阿尔敏", "利维"}}
	t.Log(b)
	t.Log(b.Spoke)
	//t.Log(b.Allen) // 不能取到
	t.Log(b.Foo.Allen) // 只能这样取到

	t.Log("------\n")

	titan := Titan{"吉克", Foo{"aaaaa", "llll"}}
	t.Log(titan)
	t.Log(titan.Zek)
	t.Log(titan.Allen)  // 可以直接取到 Foo的值
	t.Log(titan.Levy)
	t.Log(titan.Foo)
}

总结

结构体挂载方法有两种, 一种是不使用指针,这种会对实例的成员会进行值的复制, 第二种是指针,可以避免内存拷贝(所以更推荐指针方式)。

感觉go语言很大程度上继承了C语言,但是go语言指针访问结构体属性不需要
->,直接使用.属性访问,结构体挂载的两种方法,内部看起来是一样。

练习代码

https://github.com/CoderCharm/go_notes/blob/master/01_getting-started/04_Control_statements_and_functions/07_struct/03_struct/main.go

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值