Struct and Interface in Go with Examples

Published October 15, 2021

Go is a programming language that is suitable for object oriented programming approach. There are two components that can be used to implement object oriented programming including struct and interface.

Struct

Struct is a blueprint for an object. The concept of struct is similiar with class in other object oriented language. The struct has a many attributes and also methods.

This is the basic syntax to create a struct.

type struct_name struct {
    atribut_name data_type
    ..
}

In this example, the struct called Car is created to represents car entity.

package main

import (
    "fmt"
)

// create a struct
type Car struct {
    manufacturer string
    name         string
}

// create a method for Car struct
func (c *Car) run() {
    fmt.Println("Running...")
}

func main() {
    // create an object from Car struct
    var car Car = Car{
        manufacturer: "Porsche",
        name:         "911",
    }

    // call run method
    car.run()
}

Output

Running...

Based on the code above, the struct called Car is created with attributes and one method. In main() function, the object from Car struct is created then the run() method is called from car object.

This is another syntax to create an object from struct. In this syntax, the attribute name is not defined but the value of the attribute is defined.

var car Car = Car{"Porsche", "911"}

Struct Composition

In Go, the inheritance mechanism can be done with struct composition mechanism. In this example, the struct composition is used by Student struct that compose another struct called Person.

package main

import (
    "fmt"
)

// create a person struct
type Person struct {
    name string
}

// create a student struct
// this struct compose another struct called Person
type Student struct {
    Person
    courses []string
}

func (p *Person) greet() {
    fmt.Println("Hello, my name is ", p.name)
}

func main() {
    // create an object from Person struct
    var person Person = Person{name: "john doe"}

    // create an object from Student struct
    var student Student = Student{
        Person{"nathan mckane"},
        []string{"Algorithm", "Data Science"},
    }

    // call greet method from person
    person.greet()

    // call greet method from student
    student.greet()
}

Output

Hello, my name is  john doe
Hello, my name is  nathan mckane

Based on the code above, the two structs are created called Person and Student. The Student struct compose Person struct so all the methods for Person are also available for Student. In main() function, the two objects from Student and Person are created then the greet() method are called from two created objects.

Anonymous Struct

The anonymous struct is also available in Go. In this example, the anonymous struct is created.

package main

import "fmt"

func main() {
    // create an anonymous struct
    // then create an object directly
    data := struct {
        name string
        age  int32
    }{
        name: "john doe",
        age:  27,
    }

    fmt.Println("name: ", data.name)
    fmt.Println("age: ", data.age)
}

Output

name:  john doe
age:  27

Interface

Interface is a struct that only allows abstract method as an attribute. Interface is used to define certain contract that is need to be fulfilled by certain struct. A struct that implements an interface must implements all the methods that defined inside interface.

This is the basic syntax to create an interface.

type interface_name interface {
    method_name(args) return_type
    ...
}

In this example, the interface called Shape is created.

package main

import "fmt"

// create Shape interface
type Shape interface {
    area() int
}

// create rectangle struct that implements Shape interface
type Rectangle struct {
    length int
    width  int
}

// the area() method is implemented by Rectangle struct
func (r *Rectangle) area() int {
    return r.length * r.width
}

func getInfo(s Shape) {
    // the area() method will be called
    // based on the method implementation
    fmt.Println("The area: ", s.area())
}

func main() {
    // create an object from Rectangle struct
    var rectangle Rectangle = Rectangle{4, 5}

    // call getInfo function
    getInfo(&rectangle)
}

Output

The area:  20

Based on the code above, the interface called Shape is created with a abstract method called area() int. The struct called Rectangle is created and implements the area() method from Shape interface. The getInfo() function is created with Shape data type as an argument. Inside getInfo() function, the area() method is called from the argument and this method is called based on the method implementation.

Inside main() function, the object from Rectangle struct is created then the getInfo() function is called. Because the all methods inside Shape interface is implemented by Rectangle struct, so the getInfo() can be called.

Other Example using struct

When creating a function or method with many arguments, the argument can be groupped inside struct. In this example, a function called addMember() is created with too many arguments.

func addMember(name string, birthdate string, address string, age int32, hobby string) {

    // create new member data
    var newMember Member = Member{
        rand.Int(),
        name,
        birthdate,
        address,
        age,
        hobby,
    }

    // add to database
    database = append(database, newMember)
}

The too many arguments problem can be solved by creating a single struct that groups all the arguments. With using struct, the changes for the argument can be handled easily because the changes is handled in one place.

type MemberInput struct {
    name      string
    birthdate string
    address   string
    age       int32
    hobby     string
}

The addMember() function use MemberInput as an argument.

func addMember(input MemberInput) {
    // create new member data
    var newMember Member = Member{
        rand.Int(),
        input.name,
        input.birthdate,
        input.address,
        input.age,
        input.hobby,
    }

    // add to database
    database = append(database, newMember)
}

Conclusion

  • struct is a blueprint that can be used to create an object.

  • interface is a struct that only contains many abstract methods that will be implemented by certain struct. A struct that implements interface, all the methods inside interface must be implemented.

I hope this article is helpful to learn struct and interface in Go Programming Language.

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

561 Views