go的静态类型和动态类型

时间:2025-02-22 08:00:37

      先来看个简单的go程序:

package main

import (
	"fmt"
)

type TaskIntf interface {
	Process()
}
 
type Task struct {
	TaskId  string
	X int 
	Y int
}

func (p *Task)Process() {
	("%+v\n", p)
}


func main() {
	var t TaskIntf = new(Task)
	("%T\n", t)
	()
	("%+v\n", t)
}

       结果:

*
&{TaskId: X:0 Y:0}
&{TaskId: X:0 Y:0}

       

       再看:

package main

import (
	"fmt"
)

type TaskIntf interface {
	Process()
}
 
type Task struct {
	TaskId  string
	X int 
	Y int
}

func (p *Task)Process() {
	("%+v\n", p)
}


func main() {
	var t TaskIntf = new(Task)
	("%T\n", t)

	 = 1

	()
	("%+v\n", t)
}

         结果出现编译错误: undefined (type TaskIntf has no field or method X)

 

        注意到, 对于t而言,静态类型是TaskIntf,  动态类型(运行时)是Task.  而在 = 1时,编译器会进行静态检查, 故编译错误。 那怎么办呢? 可以这么搞:

package main

import (
	"fmt"
	"encoding/json"
)

type TaskIntf interface {
	Process()
}
 
type Task struct {
	TaskId  string
	X int 
	Y int
}

func (p *Task)Process() {
	("%+v\n", p)
}


func main() {
	var t TaskIntf = new(Task)
	("%T\n", t)

	str_json := `{"taskid":"xxxxxx", "x":1, "y":2}`
	([]byte(str_json), t)

	()
	("%+v\n", t)
}

        结果:

*
&{TaskId:xxxxxx X:1 Y:2}
&{TaskId:xxxxxx X:1 Y:2}

        顺便提一句, 在Task中, 变量的首字母要大写, 否则呵呵哒。

        

       还可以这么搞:

package main

import (
	"fmt"
)

type TaskIntf interface {
	Process()
	GetTask() *Task
}
 
type Task struct {
	TaskId  string
	X int 
	Y int
}

func (p *Task)Process() {
	("%+v\n", p)
}

func (p *Task)GetTask() *Task {
	return p
}

func main() {
	var t TaskIntf = new(Task)
	("%T\n", t)

	().TaskId = "xxxxxx"
	().X = 1
	().Y = 2

	()
	("%+v\n", t)
}

        结果:

*
&{TaskId:xxxxxx X:1 Y:2}
&{TaskId:xxxxxx X:1 Y:2}

 

        不多说。