About go struct initializing

package main

import (
	"fmt"
)

type Square struct {
	side float32
}

type Triangle struct {
	bottom float32
	height float32
}

type Polygon interface {
	area()
	perimeter()
}

func (square Square) area() float32 {
	return square.side * square.side
}

func (square *Square) area1() float32 {
	return square.side * square.side
}

func (triangle Triangle) area() float32 {
	return triangle.bottom * triangle.height / 2
}

func main() {
	s1 := Square{1}
	s2 := &Square{2}
	s3 := &Square{3}
	t := Triangle{1, 4}
	fmt.Println(s1.area())
	fmt.Println(s2.area())
	fmt.Println(s3.area1())
	fmt.Println(t.area())
}

what’s the difference between s1 s2 and s3

and what are the advantages & disadvantages of each type

which one is the most commonly used

HI @arianna,

s1 is a struct, whereas s2 and s3 are pointers to structs.

The difference between a type and a pointer to a type is neither marginal nor just a matter of taste or common use.

For example, if you pass s1 to a function that expects a Square, the function receives a copy of the data. If you pass s2 to a function that expects a *Square, the function receives a copy of the pointer, but this copy still points to the same data as the original s2.

If you are familiar with pointerless languages, you might know the notion of references. The concept is similar - passing data to a function by value copies this data, and passing data by reference creates a new reference to the same data.

Hence the use of pointers depends on your use case. If the receiving function shall modify the original data, you need to pass a pointer. If the function shall only read the data, pass it by value.

2 Likes

Thanks!!

A playground example: Go Playground - The Go Programming Language

So … If I return the result in functions, actually I will get the same results.
If I dont, what I pass to a function may change the original data.
Passing data doesn’t change my original data, but passing pointers do.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.