0
1

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 5 years have passed since last update.

【Go】関数の定義方法サンプルメモ

Last updated at Posted at 2020-02-11

基本の形

func <関数名>([引数]) [戻り値の型] {
    [関数の本体]
}

サンプル

sample.go
package main

import (
	"fmt"
)

// 基本の形
func plus(a int, b int) int {
	return a + b
}

// 戻り値無し
func printPlus(a int, b int) {
	fmt.Println(a + b)
}

// 戻り値&引数無し
func printDummy() {
	fmt.Println("printDummy")
}

// 戻り値複数
// 元の値と、足し算した値を返す
func plus2(a int, b int)(int, int, int){
	return a, b, a + b
}

// 可変長引数
// アンダースコア変数
// https://qiita.com/penguin_dream/items/c1df36040b3fc6d42945
func printVariable(strs ...string) {
	for _, str := range strs {
		fmt.Println(str)
	}
}

// 名前付きの戻り値
func plusMinus(a int, b int)(add int, minus int){
	add = a + b
	minus = a - b
	return
}

func main() {
	result := plus(1, 2)
	fmt.Println(result) // 3

	printPlus(2, 3) // 5

	printDummy() // printDummy

	a, b , c := plus2(1, 2)
	fmt.Println(a) // 1
	fmt.Println(b) // 2
	fmt.Println(c) // 3

	printVariable("1", "2", "3")

	add, minus := plusMinus(2, 1)
	fmt.Println(add) // 3
	fmt.Println(minus) // 1
}

参考

Go言語 - 関数 - 覚えたら書く https://blog.y-yuki.net/entry/2017/05/03/000000

改訂2版 基礎からわかる Go言語
古川 昇
シーアンドアール研究所 (2015-07-17)
売り上げランキング: 87,346
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?