Struct Embedding in ActionScript
Go supports embedding of structs and interfaces to express a more seamless composition of types. This is not to be confused with //go:embed
which is a Go directive introduced in Go version 1.16+ to embed files and folders into the application binary.
package {
import flash.display.Sprite;
public class Main extends Sprite {
public function Main() {
var co:Container = new Container();
co.base.num = 1;
co.str = "some name";
trace("co={num: " + co.num + ", str: " + co.str + "}");
trace("also num: " + co.base.num);
trace("describe: " + co.describe());
var d:Describer = co;
trace("describer: " + d.describe());
}
}
}
class Base {
public var num:int;
public function describe():String {
return "base with num=" + num;
}
}
class Container extends Sprite implements Describer {
public var base:Base = new Base();
public var str:String;
public function Container() {
// Accessing base's fields directly
this.base.num = 1;
this.str = "some name";
}
public function get num():int {
return this.base.num;
}
public function describe():String {
return this.base.describe();
}
}
interface Describer {
function describe():String;
}
A container
embeds a base
. An embedding looks like a field without a name. When creating structs with literals, we have to initialize the embedding explicitly; here the embedded type serves as the field name.
We can access the base’s fields directly on co
, e.g. co.num
. Alternatively, we can spell out the full path using the embedded type name.
Since container
embeds base
, the methods of base
also become methods of a container
. Here we invoke a method that was embedded from base
directly on co
.
Embedding structs with methods may be used to bestow interface implementations onto other structs. Here we see that a container
now implements the describer
interface because it embeds base
.