Go class basics

Recently I started using go language and somehow I can write it, so I think I'll write it like a class soon, so I'll write it here! I will write it for the time being and explain it in detail later.

main.go


package main

import "fmt"

type Human struct {
	Age  int
	Name string
}

func (h Human) getName() string {
	return h.Name
}

func (h *Human) Birthday(newAge int) {
	h.Age = newAge
}

func main() {
	v := Human{Age: 3, Name: "mike"} //Instance creation
	fmt.Println(v.getName())
	v.Birthday(24)
}

Class definition

type Human struct {
	Age  int
	Name string
}

Class definitions are defined using the concept of a structure called struct. Structures can have fields properties.

Method definition

func (h Human) getName() string {
	return h.Name
}

func (h *Human) Birthday(newAge int) {
	h.Age = newAge
}

The method associated with the class is defined as above. func (variable name class name) function name Return value { processing } It will be. go puts * next to the class name to change the value of the property in the function. This points to the address of the instance variable. You can change the actual value by changing the contents of the address variable. On the other hand, if you do not want to change the contents of the property, you do not need to use *.

Instance creation

func main() {
	v := Human{Age: 3, Name: "mike"} //Instance creation
	fmt.Println(v.getName())
	v.Birthday(24)
}

Instance creation Variable name: = class name {property name: value, .....} It will be.

It's easy, but that's it.

Recommended Posts

Go class basics
#Python basics (class)
class
class
Go Language-Basic ❶
Go language-fmt.Scan
Python basics ⑤
Linux basics
Python basics
[Learning memo] Basics of class by python
NumPy basics
Python basics ④
Go Language-Functions
Go language-pointer
Go Language-Basic ❷
Pandas basics
[Golang] Go language basics What is Goroutine?
Git basics
GO Chokisomemo 1
Python basics ③
Python basics
Django basics
Go language-iteration
Class variables
Class inheritance
Linux basics
Pandas basics
Python basics
Python basics
Python basics ③
Python basics ②
Python basics ②
Abstract class