Aller langage typé statiquement et des exemples de typage dynamique

Regardez d'abord un programme simple go:

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)
}

résultats:

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

Regardez:

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)
}

La compilation des résultats d'erreur:

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

Notez que pour t, la TaskIntf de type statique, type dynamique (exécution) est la tâche . Dans tX = 1, le compilateur vérifie statique, erreurs de compilation. Comment faire? Il propose trois façons:

La première est à ce qu'affirme l'utilisation:

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)
}

résultats:

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

Vous pouvez le faire:

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)
}

résultats:

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

vous pouvez également le faire:

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)
}

résultats:

*main.Task
&{TaskId:xxxxxx X:1 Y:2}
&{TaskId:xxxxxx X:1 Y:2}
Publié 158 articles originaux · louange gagné 119 · vues 810 000 +

Je suppose que tu aimes

Origine blog.csdn.net/u013474436/article/details/103990708
conseillé
Classement