「GO言語」関数の引数に構造体を渡すサンプル

2021年3月3日

書式
func 関数名( 変数名 構造体名)
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
var bkA Books /* 構造体Books型の変数bkA */
var bkB Books /* 構造体Books型の変数bkB */
/* 変数bkAのフィールドを設定 */
bkA.title = "Goコース"
bkA.author = "www.arkgame.com"
bkA.subject = "Go言語入門"
bkA.book_id = 1111
/* 変数bkBのフィールドを設定 */
bkB.title = "Pythonコース"
bkB.author = "www.arkgame.com"
bkB.subject = "Python言語入門"
bkB.book_id = 2222
/* bkA情報を出力 */
fmt.Println("構造体Aのメンバー変数の値:")
printBook(bkA)
/* bkB情報を出力 */
fmt.Println("構造体Bのメンバー変数の値:")
printBook(bkB)
}
func printBook( book Books ) {
fmt.Printf( "Book タイトル : %s\n", book.title)
fmt.Printf( "Book 著者 : %s\n", book.author)
fmt.Printf( "Book テーマ : %s\n", book.subject)
fmt.Printf( "Book 番号 : %d\n", book.book_id)
}
package main import "fmt" type Books struct { title string author string subject string book_id int } func main() { var bkA Books /* 構造体Books型の変数bkA */ var bkB Books /* 構造体Books型の変数bkB */ /* 変数bkAのフィールドを設定 */ bkA.title = "Goコース" bkA.author = "www.arkgame.com" bkA.subject = "Go言語入門" bkA.book_id = 1111 /* 変数bkBのフィールドを設定 */ bkB.title = "Pythonコース" bkB.author = "www.arkgame.com" bkB.subject = "Python言語入門" bkB.book_id = 2222 /* bkA情報を出力 */ fmt.Println("構造体Aのメンバー変数の値:") printBook(bkA) /* bkB情報を出力 */ fmt.Println("構造体Bのメンバー変数の値:") printBook(bkB) } func printBook( book Books ) { fmt.Printf( "Book タイトル : %s\n", book.title) fmt.Printf( "Book 著者 : %s\n", book.author) fmt.Printf( "Book テーマ : %s\n", book.subject) fmt.Printf( "Book 番号 : %d\n", book.book_id) }
package main

import "fmt"

type Books struct {
   title string
   author string
   subject string
   book_id int
}

func main() {
   var bkA Books        /* 構造体Books型の変数bkA */
   var bkB Books        /* 構造体Books型の変数bkB */

   /* 変数bkAのフィールドを設定 */
   bkA.title = "Goコース"
   bkA.author = "www.arkgame.com"
   bkA.subject = "Go言語入門"
   bkA.book_id = 1111

   /* 変数bkBのフィールドを設定 */
   bkB.title = "Pythonコース"
   bkB.author = "www.arkgame.com"
   bkB.subject = "Python言語入門"
   bkB.book_id = 2222

   /* bkA情報を出力 */
   fmt.Println("構造体Aのメンバー変数の値:")
   printBook(bkA)

   /* bkB情報を出力 */
   fmt.Println("構造体Bのメンバー変数の値:")
   printBook(bkB)
}

func printBook( book Books ) {
   fmt.Printf( "Book タイトル : %s\n", book.title)
   fmt.Printf( "Book 著者 : %s\n", book.author)
   fmt.Printf( "Book テーマ : %s\n", book.subject)
   fmt.Printf( "Book 番号 : %d\n", book.book_id)
}

実行結果
>go run sample.go
構造体Aのメンバー変数の値:
Book タイトル : Goコース
Book 著者 : www.arkgame.com
Book テーマ : Go言語入門
Book 番号 : 1111
構造体Bのメンバー変数の値:
Book タイトル : Pythonコース
Book 著者 : www.arkgame.com
Book テーマ : Python言語入門
Book 番号 : 2222

Go言語

Posted by arkgame