Struct Embedding in Visual Basic .NET

Visual Basic .NET supports the concept of inheritance and interfaces, which can be used to achieve similar functionality to struct embedding in Go. Here’s how we can represent the same concepts:

Imports System

' Base class
Public Class Base
    Public Property Num As Integer

    Public Function Describe() As String
        Return $"base with num={Num}"
    End Function
End Class

' Container class that inherits from Base
Public Class Container
    Inherits Base

    Public Property Str As String
End Class

' Interface for describing
Public Interface IDescriber
    Function Describe() As String
End Interface

Module Program
    Sub Main(args As String())
        ' When creating objects, we initialize the base class properties
        Dim co As New Container With {
            .Num = 1,
            .Str = "some name"
        }

        ' We can access the base's fields directly on co
        Console.WriteLine($"co={{num: {co.Num}, str: {co.Str}}}")

        ' We can also access the base properties explicitly
        Console.WriteLine($"also num: {co.Num}")

        ' Since Container inherits from Base, it has access to Base's methods
        Console.WriteLine($"describe: {co.Describe()}")

        ' Inheritance in VB.NET allows Container to implement IDescriber interface
        Dim d As IDescriber = co
        Console.WriteLine($"describer: {d.Describe()}")
    End Sub
End Module

In Visual Basic .NET, we use inheritance to achieve a similar effect to Go’s struct embedding. The Container class inherits from the Base class, which allows it to access all public properties and methods of Base.

When creating objects, we initialize the properties directly, as Visual Basic .NET doesn’t have a concept of anonymous structs like Go does.

The IDescriber interface is implemented implicitly by Container because it inherits from Base, which has a Describe method matching the interface.

To run this program, save it as StructEmbedding.vb and compile it using the Visual Basic compiler:

$ vbc StructEmbedding.vb
$ mono StructEmbedding.exe
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1

This example demonstrates how Visual Basic .NET uses inheritance and interfaces to achieve composition and polymorphism, which are similar concepts to struct embedding in other languages.