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

go修行13日目 Package

Posted at

Package

  • 1階層
awesomeProject/
├── main.go
└── mylib
    └── math.go

main.go


package main

import (
	"awesomeProject/mylib"
	"fmt"
)

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

math.go

package mylib

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

結果

3
  • 2階層

階層

awesomeProject/
├── main.go
└── mylib
    ├── human.go
    ├── math.go
    └── under
        └── sub.go

main.go

package main

import (
	"awesomeProject/mylib"
	"awesomeProject/mylib/under"
	"fmt"
)

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

	mylib.Say()
	under.Hello()
}

math.go

package mylib

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

human.go


package mylib

import "fmt"

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

sub.go


package under

import "fmt"

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

出力

3
Human!
Hello!

Public,Private

  • 外部から利用する場合にはPublicのように頭は大文字

main.go

package main

import (
	"awesomeProject/mylib"
	"awesomeProject/mylib/under"
	"fmt"
)

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)

	fmt.Println(mylib.Public)
	fmt.Println(mylib.private)
}

human.go

package mylib

import "fmt"

var Public string = "Public"
var private string = "private"

type Person struct {
	Name string
	Age  int
}

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

出力

  • privateは頭が小文字でunexpotedと出ている
.\main.go:19:14: cannot refer to unexported name mylib.private
.\main.go:19:14: undefined: mylib.private
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?