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

パッケージ単位でのコード管理

Goのコードは一つまたは複数のファイルで構成されるパッケージという単位で管理する。
以下のようなフォルダ構成とする。

awesomeProject
    ┣main.go
    ┣mylib
        ┣math.go
        ┣human.go
        ┣under
            ┣sub.go

math.goではint型のスライスを引数として平均値を返すAverage関数を作成する。

package mylib

func Average(s []int) int {
	total := 0
	for _, i := range s {
		total += i
	}
	return int(total / len(s))
}

human.goでは名前と年齢をフィールドに持つ構造体と文字列を出力するSay関数を作成する

package mylib

import "fmt"

type Person struct {
	Name string
	Age  int
}

func Say() {
	fmt.Println("Human!")
}

sub.goでは文字列を出力する関数を作成する。

package under

import "fmt"

func Hello() {
	fmt.Println("Hello!")
}

上記のように別フォルダで定義した関数や構造体を使用するときは、その関数が属しているパッケージをインポートする必要がある。
また、別パッケージに属する関数を利用する際は、関数の呼び出し時に「パッケージ名.関数名」としなければならない。

package main

import (
	"fmt"
	"your-module-name/awesomeProject/mylib" 
	"your-module-name/awesomeProject/mylib/under"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	fmt.Println(mylib.Average(s))

	mylib.Say()
	under.Hello()
	person := mylib.Person{Name: "Mike", Age: 20}
	fmt.Println(person)
}

//以下のように出力される
3
Human!
Hello!
{Mike 20}

関数名や構造体名、変数名など小文字にするとほかのパッケージから呼び出すことができない。そのため、ほかのパッケージから呼び出したいときは大文字で書き始めるということを忘れないようにする。

学習に使用した教材

・『入門】Golang基礎入門 + 各種ライブラリ + 簡単なTodoWebアプリケーション開発(Go言語)』M.A EduTech
https://www.udemy.com/course/golang-webgosql/?utm_medium=udemyads&utm_source=bene-msa&utm_campaign=responsive&utm_content=top-1&utm_term=general&msclkid=81e2f24a32cc185d275d953d60760226&couponCode=NEWYEARCAREERJP

・『シリコンバレー一流プログラマーが教える Goプロフェッショナル大全』酒井 潤 (著)
https://www.amazon.co.jp/%E3%82%B7%E3%83%AA%E3%82%B3%E3%83%B3%E3%83%90%E3%83%AC%E3%83%BC%E4%B8%80%E6%B5%81%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9E%E3%83%BC%E3%81%8C%E6%95%99%E3%81%88%E3%82%8B-Go%E3%83%97%E3%83%AD%E3%83%95%E3%82%A7%E3%83%83%E3%82%B7%E3%83%A7%E3%83%8A%E3%83%AB%E5%A4%A7%E5%85%A8-%E9%85%92%E4%BA%95-%E6%BD%A4/dp/4046070897

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?