Instance Methods
Lesson 24 of 48 in Coddy's GDScript for Go Developers course.
Go methods declare a receiver before the method name. A pointer receiver can mutate the original struct, whereas a value receiver receives a copy. GDScript instance methods receive self implicitly and do not declare a receiver parameter. Repeated calls act on the same instance, and aliases observe mutations. Static GDScript functions have no receiver, similar in purpose to a Go package function. The example toggles a flag rather than implementing the task numeric accumulator.
Complete Go comparison. Save the listed files in one directory and run all .go files together; package main supplies the entry point.
Go file door.go:
package main
type Door struct { Open bool }
func (d *Door) Toggle() { d.Open=!d.Open }
Go file main.go:
package main
import "fmt"
func main() { d:=Door{}; d.Toggle(); fmt.Println(d.Open) }
Go output:
trueGDScript example file demo_door.gd:
class_name DemoDoor
extends RefCounted
var open: bool = false
func toggle() -> void:
open = not openGDScript example file main.gd:
extends Node
func _ready() -> void:
var door: DemoDoor = DemoDoor.new()
door.toggle()
print(door.open)GDScript output:
trueChallenge
EasyImplement RunningTotal with value initially zero, add(amount:int)->void and read()->int. Solve adds each input integer. Separate instances stay independent.
Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.
Your code goes in running_total.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.
Try it yourself
extends Node
func contract_ok(data: Array) -> bool:
var a: RunningTotal = RunningTotal.new()
var b: RunningTotal = RunningTotal.new()
a.add(5)
a.add(-2)
if a.read() != 3 or b.read() != 0: return false
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in GDScript for Go Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command Count5Objects and State
Scripts as ClassesInitializationInstance MethodsRecap: Independent BasketsProperty SettersPractice on your own: Online GDScript compiler