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?

More than 1 year has passed since last update.

Go 関数 基礎固め

Last updated at Posted at 2023-07-19

名前付き関数

package main

import (
	"fmt"
)

func Plus(x int, y int) int { // ()intは引数の型と 外のintは返り値の型
	return x + y //int型の返り値 returnで値を返す時は 返り値の型を指定する必要になる
}

func Div(x,y int) (int, int) {
	q := x / y
	r := x % y
	return q, r //返り値が二つある だから(int, int)
}

func Double(price int) (result int) { //返り値に変数も指定できる。変数resultを宣言。
	result = price * 2 //resultにpriceの2倍の値を入れる
	return //(result int)で指定してるのでreturnの中身は省略できる
}

func Noreturn() { //返り値がない関数
	fmt.Println("No Return")
	return
}

func main() {

i := Plus(1, 2)
fmt.Println(i)

i2, i3 := Div(9, 3)
fmt.Println(i2, i3)

i4, _ := Div(12, 3) // _にすることで返り値を破棄できる。qの値だけを受け取ることができる。rは破棄。
fmt.Println(i4)

i5 := Double(1000)
fmt.Println(i5)

Noreturn()
}

コンソール go run main.go

3
3 0
4
2000
No Return

無名関数

package main

import (
	"fmt"
)

// 無名関数

func main() {
	f := func(x, y int) int {
		return x + y
	}
	i := f(1, 2)
	fmt.Println(i)  // 3

	i2 := func(x, y int) int {
		return x + y
	}(3, 2) //引数を渡している

	fmt.Println(i2) // 5
}
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?