Sobes.tech
Middle

How can you create custom types based on structures in Go?

sobes.tech AI

Answer from AI

In Go, you can create custom types based on structs by declaring a new type that uses the struct as its base. This allows you to add methods to the new type and use it as a separate data type.

Example:

package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

// Create a new type Employee based on Person

type Employee Person

func (e Employee) Greet() {
    fmt.Printf("Hello, my name is %s and I am %d years old.\n", e.Name, e.Age)
}

func main() {
    emp := Employee{Name: "Ivan", Age: 30}
    emp.Greet()
}

In this example, Employee is a new type based on the Person struct. We can add methods to Employee without modifying the original struct.

How can you create custom types based on structures… - sobes.tech