string
}
func (this *name1) String() string {
return fmt.Sprintf("This is String(%s).", this.string)
}
func main() {
n := new(name1)
fmt.Println(n) //This is String().
n.string = "suoning"
d := fmt.Sprintf("%s", n) //This is String(suoning).
fmt.Println(d)
}
defer所有错误
func myE() (str string, err error) {
defer func() {
if p := recover(); p != nil {
str, ok := p.(string)
if ok {
err = errors.New(str)
} else {
err = errors.New("panic")
}
//debug.PrintStack()
}
}()
panic("this is panic message")
return "hello girl", err
}
接口Interface
Interface类型可以定义一组方法,但是这些不需要实现。并且interface不能包含任何变量。
interface类型默认是一个指针。
Interface定义
type Car interface {
NameGet() string
Run(n int)
Stop()
}
Interface实现
- Golang中的接口,不需要显示的实现。只要一个变量,含有接口类型中的所有方法,那么这个变量就实现这个接口。因此,golang中没有implement类似的关键字;
- 如果一个变量含有了多个interface类型的方法,那么这个变量就实现了多个接口;如果一个变量只含有了1个interface的方部分方法,那么这个变量没有实现这个接口。
- 空接口 Interface{}:空接口没有任何方法,所以所有类型都实现了空接口。
var a int
var b interface{} //空接口
b = a
多态
一种事物的多种形态,都可以按照统一的接口进行操作。
栗子:
type Car interface {
NameGet() string
Run(n int)
Stop()
}
type BMW struct {
Name string
}
func (this *BMW) NameGet() string {
return this.Name
}
func (this *BMW) Run(n int) {
fmt.Printf("BMW is running of num is %d \n", n)
}
func (this *BMW) Stop() {
fmt.Printf("BMW is stop \n")
}
type Benz struct {
Name string
}
func (this *Benz) NameGet() string {
return this.Name
}
func (this *Benz) Run(n int) {
fmt.Printf("Benz is running of num is %d \n", n)
}
func (this *Benz) Stop() {
fmt.Printf("Benz is stop \n")
}
func (this *Benz) ChatUp() {
fmt.Printf("ChatUp \n")
}
func main() {
var car Car
fmt.Println(car) // <nil>
var bmw BMW = BMW{Name: "宝马"}
car = &bmw
fmt.Println(car.NameGet()) //宝马
car.Run(1) //BMW is running of num is 1
car.Stop() //BMW is stop
benz := &Benz{Name: "大奔"}
car = benz
fmt.Println(car.NameGet()) //大奔
car.Run(2) //Benz is running of num is 2
car.Stop() //Benz is stop
//car.ChatUp() //ERROR: car.ChatUp undefined (type Car has no field or method ChatUp)
}
Interface嵌套
一个接口可以嵌套在另外的接口。
即需要实现2个接口的方法。
type Car interface {
NameGet() string
Run(n int)
Stop()
}
type Used interface {
Car
Cheap()
}
类型断言
类型断言,由于接口是一般类型,不知道具体类型,
如果要转成具体类型,可以采用以下方法进行转换:
var t int
var x interface{}
x = t
y = x.(int) //转成int
y, ok = x.(int) //转成int,不报错
栗子一:
func test(i interface{}) {
// n := i.(int)
n, ok := i.(int)
if !ok {
fmt.Println("error")
return
}
n += 10
fmt.Println(n)
}
func main() {
var t1 int
test(t1)
}
栗子二:
switch & type
type Student struct {
Name string
}
func judgmentType(items ...interface{}) {
for k, v := range items {
switch v.(type) {
case string:
fmt.Printf("string, %d[%v]\n", k, v)
case bool:
fmt.Printf("bool, %d[%v]\n", k, v)
case int, int32, int64:
fmt.Printf("int, %d[%v]\n", k, v)
case float32, float64:
fmt.Printf("float, %d[%v]\n", k, v)
case Student:
fmt.Printf("Student, %d[%v]\n", k, v)
case *Student:
fmt.Printf("Student, %d[%p]\n", k, v)
}
}
}
func main