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