Go statically typed language and dynamic typing examples

First look at a simple go program:

package main
 
import (
	"fmt"
)
 
type TaskIntf interface {
	Process()
}
 
type Task struct {
	TaskId  string
	X int 
	Y int
}
 
func (p *Task)Process() {
	fmt.Printf("%+v\n", p)
}
 
 
func main() {
	var t TaskIntf = new(Task)
	fmt.Printf("%T\n", t)
	t.Process()
	fmt.Printf("%+v\n", t)
}

result:

*main.Task
&{TaskId: X:0 Y:0}
&{TaskId: X:0 Y:0}

Look:

package main
 
import (
	"fmt"
)
 
type TaskIntf interface {
	Process()
}
 
type Task struct {
	TaskId  string
	X int 
	Y int
}
 
func (p *Task)Process() {
	fmt.Printf("%+v\n", p)
}
 
 
func main() {
	var t TaskIntf = new(Task)
	fmt.Printf("%T\n", t)
 
	t.X = 1
 
	t.Process()
	fmt.Printf("%+v\n", t)
}

The results compilation error:

t.X undefined (type TaskIntf has no field or method X)

Note that for t, the static type TaskIntf, type dynamic (runtime) is the Task . In tX = 1, the compiler checks static, so compilation errors. then what should we do? It provides three ways:

The first is to use assertions:

package main
 
import (
	"fmt"
)
 
type TaskIntf interface {
	Process()
}
 
type Task struct {
	TaskId  string
	X int 
	Y int
}
 
func (p *Task)Process() {
	fmt.Printf("%+v\n", p)
}
 
 
func main() {
	var t TaskIntf = new(Task)
	fmt.Printf("%T\n", t)
 
	t.(*Task).X = 1
 
	t.Process()
	fmt.Printf("%+v\n", t)
}

result:

*main.Task
&{TaskId: X:1 Y:0}
&{TaskId: X:1 Y:0}

You can do so:

package main
 
import (
	"fmt"
	"encoding/json"
)
 
type TaskIntf interface {
	Process()
}
 
type Task struct {
	TaskId  string
	X int 
	Y int
}
 
func (p *Task)Process() {
	fmt.Printf("%+v\n", p)
}
 
 
func main() {
	var t TaskIntf = new(Task)
	fmt.Printf("%T\n", t)
 
	str_json := `{"taskid":"xxxxxx", "x":1, "y":2}`
	json.Unmarshal([]byte(str_json), t)
 
	t.Process()
	fmt.Printf("%+v\n", t)
}

result:

*main.Task
&{TaskId:xxxxxx X:1 Y:2}
&{TaskId:xxxxxx X:1 Y:2}

Also you can do so:

package main
 
import (
	"fmt"
)
 
type TaskIntf interface {
	Process()
	GetTask() *Task
}
 
type Task struct {
	TaskId  string
	X int 
	Y int
}
 
func (p *Task) Process() {
	fmt.Printf("%+v\n", p)
}
 
func (p *Task) GetTask() *Task {
	return p
}
 
func main() {
	var t TaskIntf = new(Task)
	fmt.Printf("%T\n", t)
 
	t.GetTask().TaskId = "xxxxxx"
	t.GetTask().X = 1
	t.GetTask().Y = 2
 
	t.Process()
	fmt.Printf("%+v\n", t)
}

result:

*main.Task
&{TaskId:xxxxxx X:1 Y:2}
&{TaskId:xxxxxx X:1 Y:2}
Published 158 original articles · won praise 119 · views 810 000 +

Guess you like

Origin blog.csdn.net/u013474436/article/details/103990708