Home >Backend Development >Golang >Allow using composites as function parameters in structures

Allow using composites as function parameters in structures

WBOY
WBOYforward
2024-02-05 22:30:031158browse

Allow using composites as function parameters in structures

Question content

Let's say I'm making something like a game engine.

I need a GameObject structure to define some event handlers:

type GameObject struct {
    transform        Transform
    animatedMesh     AnimatedMesh
    updateHandler    func(self GameObjectGetter)
    onCreateHandler  func(self GameObjectGetter)
    onDestroyHandler func(self GameObjectGetter)
}


func (g GameObject)getGameObject() GameObject {
    return g
 }

 type GameObjectGetter interface {
    getGameObject() GameObject
 }

Then when I initialize some specific game objects, I want to define the handler as a custom function:

g.updateHandler = func(self FishGameObject) {  // Error here
    self.tailMotionSpeed = self.boid.acceleration.Normalize().Len()
}

Please note that tailMotionSpeed and boid are not members of GameObject. They are members of struct FishGameObject, which has some custom properties and an anonymous GameObject:

type FishGameObject struct {
    leftFinPosition  float32
    rightFinPosition float32
    tailMotionSpeed  float32
    boid             Boid
    GameObject
}

If I specify the parameter as GameObjectGetter, I get the error self.tailMotionSpeed ​​undefined (type GameObjectGetter has no field or method tailMotionSpeed) , and I get the error cannot use handler (type func (variable of self FishGameObject) )) as the value of func(self GameObjectGetter) in the struct literal (if I specify the parameter as FishGameObject). what do I do?


Correct answer


What you want to do is not possible in Go the way you want to do it. However, you can do this:

Define GameObject as interface:

type GameObject interface {
   GetTransform() *Transform
   GetAnimatedMesh() *AnimatedMesh
   SetUpdateHandler(func(GameObject))
   UpdateHandler() func(GameObject)
   ...
}

You can define a BaseGameObject:

type BaseGameObject struct {
    transform        Transform
    animatedMesh     AnimatedMesh
    updateHandler    func(GameObject)
    onCreateHandler  func(GameObject)
    onDestroyHandler func(GameObject) 
}

Define all methods so that BaseGameObject becomes GameObject.

Then, define FishGameObject like you did, but

fish.SetUpdateHandler(func(self GameObject) {  
    fish:=self.(*FishGameObject)
     ...
   })

You should also use pointer receivers for all methods.

The above is the detailed content of Allow using composites as function parameters in structures. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete