Go language learning Day06

Today, learning interface and other things.

package main

import (
	"fmt"
	"math"
)

type I interface {
	M()
}

type T struct {
	S string
}

func (t *T)M(){
	fmt.Println(t.S)
}

type F float64

func (t F)M(){
	fmt.Println(t)
}

func describe(i I){
	fmt.Printf("(%v,%T)\n",i,i)
}

func main(){
	var i I

	i = &T{"Hello"}
	describe(i)
	i.M()

	i = F(math.Pi)
	describe(i)
	i.M()
}

Next is today's learning the code:

package main

import (
	"fmt"
)

type I interface {
	M()
}

type T struct {
	S string
}

func (t *T)M(){
	if t==nil{
		fmt.Println("<nil>")
		return
	}
	fmt.Println(t.S)
}

func main(){
	var i I
	var t *T
	i = t
	describe(i)
	i.M()

	i = &T{"hello"}
	describe(i)
	i.M()

}

func describe(i I)  {
	fmt.Printf("(%v,%T)\n",i,i)
}

package main

import "fmt"

type I interface {
	M()
}

func main(){
	var i I
	describe(i)
	i.M() //当未具体实现接口的方法时候,会自动报错

}

func describe(i I)  {
	fmt.Printf("(%v,%T)\n",i,i)
}
package main
import (
	"fmt"
	"io"
	"strings"
)

func main() {
	r := strings.NewReader("Hello, Reader!")

	b := make([]byte, 8)
	for {
		n, err := r.Read(b)
		fmt.Printf("n = %v err = %v b = %v\n", n, err, b)
		fmt.Printf("b[:n] = %q\n", b[:n])
		if err == io.EOF {
			break
		}
	}
}
//接口断言
//即判断数据类型
package main

import (
	"fmt"
)

func main(){
	var i interface{} = "hello"
	s:=i.(string)
	fmt.Println(s)

	s,ok :=i.(string)
	fmt.Println(s,ok)
	f,ok := i.(float64)
	fmt.Println(f,ok)
}

package main

import "fmt"

func do(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Printf("Twice %v is %v\n", v, v*2)
	case string:
		fmt.Printf("%q is %v bytes long\n", v, len(v))
	default:
		fmt.Printf("I don't know about type %T!\n", v)
	}
}

func main() {
	do(21)
	do("hello")
	do(true)
}
package main

import "fmt"

//声明接口
type I interface {
	M()
}

//声明结构体
type T struct {
	S string
}

//类型T实现了M方法,但无需显示调用
func (t T)M(){
	fmt.Println(t.S)
}

func main() {
	var i I = T{"hello"}
	i.M()
}

Which is now the basis of a concurrent course left the last school yet, in my opinion, this may be the soul of the Go language, and so there is a good time to summarize some of the important points about the Go interface! Then prepare to take out the Python project, can today hope to win this one, Come on Come on Come on! ! !

Guess you like

Origin blog.csdn.net/Giser_D/article/details/92375405