Struct Embedding in Scilab
Scilab supports structured programming, but it doesn’t have a direct equivalent to Go’s struct embedding. Instead, we’ll use a similar concept of composing structures and functions.
// Define a base structure
function base = createBase(num)
base.num = num;
endfunction
// Define a describe function for base
function str = describeBase(base)
str = sprintf("base with num=%d", base.num);
endfunction
// Define a container structure that includes base
function container = createContainer(num, str)
container.base = createBase(num);
container.str = str;
endfunction
// Main function
function main()
// Create a container
co = createContainer(1, "some name");
// Access fields directly
printf("co={num: %d, str: %s}\n", co.base.num, co.str);
// Access using full path
printf("also num: %d\n", co.base.num);
// Call the describe function
printf("describe: %s\n", describeBase(co.base));
// In Scilab, we don't have interfaces, but we can demonstrate
// similar behavior by passing our container to a function
// that expects a base structure
function printDescription(obj)
printf("describer: %s\n", describeBase(obj.base));
endfunction
printDescription(co);
endfunction
// Run the main function
main();
To run this Scilab script, save it to a file (e.g., struct_composition.sce
) and execute it in Scilab:
--> exec('struct_composition.sce')
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1
In this Scilab version:
We define structures using functions that return a structure (e.g.,
createBase
,createContainer
).Instead of methods, we use separate functions that take the structure as an argument (e.g.,
describeBase
).We simulate composition by including one structure inside another.
We don’t have direct method invocation on structures, so we call functions passing the structure as an argument.
Scilab doesn’t have interfaces, so we demonstrate a similar concept by creating a function that accepts any structure with a
base
field.
This example shows how to create composite structures and work with them in Scilab, which is conceptually similar to struct embedding in Go, albeit with different syntax and capabilities.