go结构体方法

Golang中的方法是作用在特定类型的变量上,因此自定义类型,都可以有方法,而不仅仅是struct。

结构体是用户单独定义的类型,不能和其他类型进行强制转换

定义格式

func (var *Struct_Name) FuncName( var0, var1... )  return type {}
package main

import (
	"fmt"
)

type test struct {
	name string
	age  int
}

func (v *test) getList() {
	fmt.Println("getList")
}

func main() {
	var s = new(test)

	s.getList()
}

golang中结构体方法没有构造函数,可以自己定义并执行构造函数

package main

import (
	"fmt"
)

type test struct {
	name string
	age  int
}

func (this *test) init(name string, age int) {
	this.name = name
	this.age = age
}

func (this *test) getName() string {
	return this.name
}

func (this *test) getAge() int {
	return this.age
}

func main() {
	var s = new(test)

	s.init("zhangsan", 20)

	fmt.Println(s.getName())
	fmt.Println(s.getAge())
}

猜你喜欢

转载自www.cnblogs.com/LC161616/p/9903481.html