0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Go言語入門】-メソッド編-

Posted at

はじめに

今回はメソッドについてまとめて見たいと思います。

メソッド

ドットで呼び出せるものをメソッドという

type Test struct {
	X, Y int
}

func (v Test) capa() int {
	return v.X + v.Y
}

func main() {
	v := Test{2, 4}
	fmt.Println(v.capa())
}

// 出力結果
6

コンストラクタ

type Test struct {
	x, y int
}

func New(x, y int) *Test{
return &Test{x,y}

}

func (v Test) Scale() int{
	return v.x * v.y
}

func main() {
	v := New(2,4)
	fmt.Println(v.Scale())
}

// 出力結果
8

Embedded

継承的な使い方ができる

type Test struct {
	x, y int
}

type Test2 struct {
	Test
	z int
}

func New(x, y, z int) *Test2{
return &Test2{Test{x,y},z}

}

func (v Test2) Scale() int{
	return v.x * v.y *v.z
}

func main() {
	v := New(2,4,5)
	fmt.Println(v.Scale())
}

// 出力結果
40

interface

type People interface {
	Test()
}

type Person struct {
	Age int
}

func (p Person) Test() {
	fmt.Println(p.Age)
}

func main() {
	var taro People = Person{11}
	taro.Test()
}

// 出力結果
11

タイプアサーションとSwitch Type文

func do(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Println(2 * v)
	case string:
		fmt.Println("Hello" + v)
	case bool:
		fmt.Println(!v)
	default:
		fmt.Println(v)
	}
}

func main() {
	do(1)
	do("World")
	do(false)
}

// 出力結果
2
HelloWorld
true
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?