Tips for using Go for beginners (notes and references)
The use of packages in golang is different from python. To split a project in .go files, one can put them in the same folder as the main program (usually the name of the project or main.go), or inside subfolders.
Relative imports are forbidden after Go 1.11, so this is the recippe:
Consider a project named "go_game_jumper" with this tree:
go_game_jumper\
go_game_jumper\main.go
go_game_jumper\auxiliary.go
go_game_jumper\src\tiles\tiles.go
To import, one must name the packages as the name of the parent folder (recommended to ease the namespace thing, but not obligatory):
auxiliary.go:
package main
...
main.go:
package main
import (
"fmt"
"log"
"go_game_jumper/src/tiles"
var demo mytiles.Test = 10 // declared a var demo of type Test, which is equivalent to an integer
...
tiles.go:
package mytiles
type Test int
...
TLDR: You should import subfolders based on the project main name. And the .go files defines the namespace (the namespace is the "y" in "import x as y" in python, for reference). So to use the namespace in main one must see the package name declared in the subfolder "tiles" in the example above.
One thing to note is that only exported types and functions in a will be available externally. That is, types and functions whose names begin with a capital letter.
To simplify the usage of types from external packages by assigning them to a shorter alias.
Copy code
package main
import (
"fmt"
"log"
t "go_game_jumper/src/tiles" // Import the tiles package and assign an alias "t"
"github.com/hajimehoshi/ebiten"
"github.com/hajimehoshi/ebiten/ebitenutil"
)
// ...
// the player
var player t.Tile = t.Tile{ // Use the alias "t" here
image: nil,
x: 50,
y: 50,
vx: 0,
vy: 0,
width: 16,
height: 16,
standing: true,
blocking: true,
}
By assigning the alias "t" to the tiles package, you can use "t.Tile" to refer to the "Tile" type throughout your "main.go" file. Use meaningful names to avoid confusion.
An interface may be created to deal with similar types that embbeds the same methods, for example:
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func PrintArea(s Shape) {
fmt.Println("Area:", s.Area())
}
func main() {
c := Circle{Radius: 5}
r := Rectangle{Width: 3, Height: 4}
PrintArea(c) // Prints the area of the circle
PrintArea(r) // Prints the area of the rectangle
}