Structs in Visual Basic .NET

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

Here’s an example of how you can achieve similar functionality in Visual Basic .NET using Classes:

Imports System

' This Person class has Name and Age fields.
Public Class Person
    Public Property Name As String
    Public Property Age As Integer

    ' Constructor to initialize a new Person with the given name.
    Public Sub New(name As String)
        Me.Name = name
        Me.Age = 42 ' Default age for the example
    End Sub

    ' Overriding the ToString method for a custom display format.
    Public Overrides Function ToString() As String
        Return $"{Name} {Age}"
    End Function
End Class

Module Program
    Sub Main()
        ' This syntax creates a new class instance.
        Console.WriteLine(New Person("Bob") With {.Age = 20}.ToString())

        ' You can name the fields when initializing a class instance.
        Console.WriteLine(New Person("Alice") With {.Age = 30}.ToString())

        ' Omitted fields will have their default values.
        Console.WriteLine(New Person("Fred").ToString())

        ' Getting a reference to the class instance.
        Dim ann As New Person("Ann") With {.Age = 40}
        Console.WriteLine(ann.ToString())

        ' Encapsulating new class creation in a function
        Console.WriteLine(NewPerson("Jon").ToString())

        ' Access class fields with a dot.
        Dim sean As New Person("Sean") With {.Age = 50}
        Console.WriteLine(sean.Name)

        ' You can also use dots with class references - no dereferencing needed.
        Dim sp As Person = sean
        Console.WriteLine(sp.Age)

        ' Class instances are mutable.
        sp.Age = 51
        Console.WriteLine(sp.Age)

        ' Using an anonymous class for temporary data structures.
        Dim dog = New With {.Name = "Rex", .IsGood = True}
        Console.WriteLine(dog.ToString())
    End Sub

    ' Function to construct a new Person instance with a given name.
    Function NewPerson(name As String) As Person
        Dim p As New Person(name)
        p.Age = 42
        Return p
    End Function
End Module

This example showcases how to use Classes in Visual Basic .NET to group and manage data with properties and methods, including initialization, default values, and creating instances both with and without constructors. It also demonstrates mutability, references, and using anonymous classes for temporary data structures.