Why is string.erase() a void?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Overloaded

Hello! I’m curious as to how string.erase() works. I’m trying to remove characters from a string (let’s call it strName) from a specific location inside the string.

But when I do strName = strName.erase(2, 3), it returns an error saying “Assigned value type (null) doesn’t match the variable’s type (String)”. If I just do strName.erase(2, 3), it doesn’t seem to do anything. From what I’ve seen in the documentation, erase is the only void method in the string class. Any ideas as to why this is? Am I doing something wrong, or it should be returning a string and not void? Thanks! I’m using Godot Engine v3.1 stable.mono.official (GDScript)

:bust_in_silhouette: Reply From: Calinou

This is because String.erase() is an in-place method, which means it modifies the variable the method is run on.

func _ready():
    var some_string = "foobar"
    some_string.erase(0, 3)
    print(some_string) # Prints "bar"

A few other methods in Godot work like this; I suppose it would be good in the long run to make them immutable (meaning they return a new instance of the modified data, and keep the original unmodified), but this is a compatibility-breaking change.