go语言接口使用

go语言中没有java中的extends,也没有class的概念,“继承”的概念体现的结构体struct文件的方法中

package main

import (
	"fmt"
)
// 定义接口,
// 该接口可以定在在该文件类或者其他文件夹内,类型java的接口,只定义方法,没有实现
type LessAdder interface {
	GetById(id int64) Product
	Add() bool
}

//——————————以下是接口的实现——————————————————
// 定义一个结构体,类型java对象,不过没有getter,setter方法
type Product struct {
	id int64
	name string
}

func (a Product) GetById(id int64) Product {
	product := Product{id: 1, name: "make"}
	return product
}
func (a *Product) Add() bool{
	return true
}

func main() {
	var a Product
	var b1 LessAdder = &a           //OK,类似于java中多态:的向上造型
	fmt.Println(b1.GetById(1)) //输出:{1 make}
}


猜你喜欢

转载自blog.csdn.net/weixin_42752859/article/details/86634232