Menu
CoddyTech

Scripts as Classes

Lesson 22 of 48 in Coddy's GDScript for Go Developers course.

Go structs are value types, and assignment copies their fields. A pointer to a struct instead shares that existing value. GDScript ordinary object assignment shares a reference. Its file defines a script class, class_name registers a global name and extends selects a base. The Go comparison deliberately aliases a pointer rather than copying the struct. GDScript RefCounted helpers need no scene node; keep each globally named helper in its own file.

Complete Go comparison. Save the listed files in one directory and run all .go files together; package main supplies the entry point.

Go file token.go:

package main
type Token struct { Text string }

Go file main.go:

package main
import "fmt"
func main() { a:=&Token{Text:"blue"}; b:=a; b.Text="gold"; fmt.Println(a.Text) }

Go output:

gold

GDScript example file demo_token.gd:

class_name DemoToken
extends RefCounted
var text: String = "blue"

GDScript example file main.gd:

extends Node

func _ready() -> void:
	var a: DemoToken = DemoToken.new()
	var b: DemoToken = a
	b.text = "gold"
	print(a.text)

GDScript output:

gold
challenge icon

Challenge

Easy

Define ParcelRecord with weight:int initially 0 and label:String initially empty. Solve creates two records, sets the first from [label,weight], and returns label:weight:second_weight. Fields must be 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 parcel_record.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: ParcelRecord = ParcelRecord.new()
	var b: ParcelRecord = ParcelRecord.new()
	if a.weight != 0 or a.label != "": return false
	a.weight = 7
	if b.weight != 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for Go Developers

Practice on your own: Online GDScript compiler