Go Structs and Interfaces

Created At: 2023-05-01 18:07:45 Updated At: 2023-05-02 07:59:58

Just like other programming languages Go provides better way to put all the data or variables or fileds together. In Go we don't have a class.

The similar in Go is called Struct.

Structs just like classes holds variables or fields or data or other structs just like the classes do.

So you can think of struct as your class. To declare struct you just simple do like below 

type Circle struct {
  x float64
  y float64
  r float64
}

So you have to start with the type keyword and finish with struct keyword. In between you have a custom name. You can name it anything.

With the above struct we would be to instantiate Circle struct, pass variable and even calculate the area of the Circle.

Let's first see how to initialize the Circle struct. The simplest and easiest way to do is to

c := Circle{0, 0, 5}

So here we created a variable c and assigned the Circle as an object. We also passed value for the Circle objects. As we passed the values, we did not mention the name of the variable. We just maintained the order. 

If you don't mention field's name, you must maintain the order.

If you don't want to maintain the order, you need to pass the value with field's name.

c := Circle{x: 0, y: 0, r: 5}

You can access the fields value using dot (.) operator. This is just like any other programming language. 

You can access it like below

fmt.Println(c.r)

It would print 5 on the terminal. 

Now take a look at the total code so far

Now we will define a new function to calculate the area of the Circle. Let's see the function

func area(c Circle) float64 {
	a := c.r * c.r
	return a
}

The above function takes Circle as a parameter and calculates the area and return the area. Now our total program looks like below

type Circle struct {
	x float64
	y float64
	r float64
}

func area(c Circle) float64 {
	a := math.Pi * c.r * c.r
	return a
}
func main() {
	c := Circle{0, 0, 5}
	fmt.Println(c.r)
	a := area(c)
	fmt.Println(a)
}

We can also make area() function better, by making it a receiver function. It's a special type of function, but we rather call it method. Look at this method first

go method

This is our new function or method. It's better to call it method since it's a convention in Go. Here the part in red box makes it method, we also call this type of function a receiver function. So now area() is receiver function. Receiver has to have a pointer type.

I understand it like below

Now any Circle object can call this area() method from any where as long as there's a Circle object. It's more like area() method is part of Circle struct.

So that's what we will do. We will call area() method from our main().

We called the area() method using a dot operator.

Comment

Add Reviews