Skip to content

Elegantly solve the problem of pointers modifying data incorrectly #74301

Closed as not planned
@luchaoshi45

Description

@luchaoshi45

Go does not allow const pointers #6386

type Vector3Float struct {
  float x = 1;
  float y = 2;
  float z = 3;
}

type WPositionComponent struct {
	pos                 *Vector3Float
}
func (c *WPositionComponent) GetPos() *protocol.Vector3Float {
	return c.pos
}
func main(){
  wpc := WPositionComponent{posptr}
  // Get pointer
  pos := wpc.GetPos()
  // Allow
  fmt.Println(pos.x)
  // Do Not Allow, It is stipulated that the value can only be changed through the SetPos function
  pos.x = 666
}

GetPos() returns a pointer. The current modification plan is to return a slice of [x, y, z], but there are problems

  1. The project is relatively complex. There are 458 calls to GetPos(). It is necessary to modify 458 callers, which is a huge workload
  2. Returning a slice affects memory performance, involves the call stack, and the return value consumes more memory, affecting the performance of the server

Metadata

Metadata

Assignees

No one assigned

    Labels

    LanguageProposalIssues describing a requested change to the Go language specification.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions