`

interface

    博客分类:
  • go
 
阅读更多
package main

import (
	"fmt"
)

//相当于接口类和虚函数
type phone interface {
	desc(string) int32
	update_price(string)
}

type iphone struct {
	price string
}

func (iphone1 iphone) desc(name string) int32 {
	fmt.Printf("this is %v iphone,price:%v\n", name, iphone1.price)
	return 1
}

//指针可以修改数据
func (iphone1 *iphone) update_price(p string) {
	iphone1.price = p
}

type android struct {
	price string
}

//值传递是改不了数据的
func (android1 android) update_price(p string) {
	android1.price = p
}

func (android1 android) desc(name string) int32 {
	fmt.Printf("this is %v android,price:%v\n", name, android1.price)
	return 2
}

func main() {
	var phone1 iphone
	phone1.update_price("5000")
	fmt.Println(phone1.desc("zhangsans")) //this is zhangsans iphone,price:5000\n 1
	var phone2 android
	phone2.update_price("4000")
	fmt.Println(phone2.desc("lisi")) //this is lisi android,price:\n 2
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics