Go面向对象编程笔记
常用类型与string转换
strconv包实现了基本数据类型和其字符串表示的相互转换。
package main
import (
"fmt"
"strconv"
)
func main() {
var num1 int=90;
var num2 float64=23.456;
var b bool =true;
// var myChar byte='h'
var str string//空的字符串
str=fmt.Sprintf("%d",num1);
fmt.Printf("%T %v\n",str,str);
str=fmt.Sprintf("%.3f",num2);
fmt.Printf("%T %v\n",str,str);
str=fmt.Sprintf("%t",b);
fmt.Printf("%T %q\n",str,str);
//char 转位
//strconv包实现了基本数据类型和其字符串表示的相互转换。具体详见文档
str="1111";
var num int64;
num,_=strconv.ParseInt(str,10,64);
fmt.Printf("%T %v\n",num,num);
}
Go继承
package main
import "fmt"
type user struct {
name string
password string
}
type person struct {
id string
}
type admin struct {
user
person
tag string
}
//这里为结构体中的函数
func (u user) checkPassword(password string) bool {
return u.password == password
}
func (u *user) resetPassword(password string) {
u.password = password
}
func main() {
a := user{name: "wang", password: "1024"}
a.resetPassword("2048")
fmt.Println(a.checkPassword("2048")) // true
var adm admin
adm.name = "name"
adm.password = "password"
adm.tag = "tag"
adm.resetPassword("20")
adm.id = "身份证"
fmt.Println(adm)
}
接口
package main
import (
"fmt"
)
//声明,定义一个接口
type usb interface {
//声明了两个没有实现的方法
start()
stop()
}
type phone struct{}
//让phone 实现usb接口
func (p phone) start() {
fmt.Println("手机开始工作")
}
func (p phone) stop() {
fmt.Println("手机停止工作")
}
type canera struct{}
func (c canera) start() {
fmt.Println("相机 start")
}
func (c canera) stop() {
fmt.Println("相机 stop ")
}
type computer struct {
}
//只要是实现了usb接口声明的所有方法
func (c computer) working(usb usb) {
usb.start()
usb.stop()
}
func main() {
//测试
c := computer{}
phone := phone{}
camera := canera{}
c.working(phone)
c.working(camera)
}
本文作者:可可爱爱奇奇怪怪。。。
本文链接:https://www.cnblogs.com/ccsuf/p/16262014.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。