Golang pass interface by reference

Golang pass interface by reference


‘Golang pass interface by reference’? In Go, interfaces are typically passed by value, meaning that a copy of the interface value is passed to a function or assigned to a variable. However, since interfaces contain a pair of values (a type and a value), it may appear as if they are passed by reference. In reality, what’s being passed is a copy of the interface’s type and value pair.

Here’s a brief explanation of how interfaces work in Go and why they are effectively passed by reference:

1. Interface Basics:

In Go, an interface is a set of method signatures. A variable of an interface type can hold any value that implements these methods.

The zero value of an interface is nil.

2. Interface Value:

An interface value consists of a pair: a type and a value. The type specifies the concrete type that implements the methods, and the value is the actual data of that type.

3. Passing Interfaces:

When an interface is passed to a function, a copy of the interface’s type and value is created.

However, since the value held by the interface is a reference to the underlying data (e.g., a pointer), modifications made to the data inside the function are visible outside.

Simple example to illustrate this concept:

package main

import "fmt"

// Printer interface with a Print method
type Printer interface {
    Print()
}

// MyStruct implements the Printer interface
type MyStruct struct {
    Data string
}

// Print method for MyStruct
func (m *MyStruct) Print() {
    fmt.Println(m.Data)
}

// Function that takes an interface parameter
func modifyInterface(p Printer) {
    // The value inside the interface is a reference to the original data
    myStruct := p.(*MyStruct)
    myStruct.Data = "Modified Data"
}

func main() {
    original := &MyStruct{Data: "Original Data"}

    // Pass the interface by value
    modifyInterface(original)

    // Modifications are visible outside the function
    original.Print() // Prints: Modified Data
}

In this example, modifyInterface takes an interface parameter. Although the interface is passed by value, the modifications made to the underlying data are reflected outside the function. This behavior is possible because the interface holds a reference to the underlying data.

Final Point

In summary, while interfaces in Go are passed by value, they often contain references to underlying data, giving the appearance of passing by reference. Understanding the mechanics of interfaces helps in working effectively with Go’s unique approach to types and interfaces.

You May Also Like: