golang introduction
// Compile file
go build
// Test (*_test.go)
go test
// formatting
go fmt
// install package
go get
// analysis possible bug
go vert
// quickly build and run
go run
// show go document
godoc
// variable v1
var name string
name = "Stanney"
// variable v2
name := "Stanney"
// const
const PI = 3.14159
var
const
func
type
package main
import (
"fmt"
)
type Point struct {
x float64
y float64
}
func main() {
p := Point{x: 3.0, y: 4.0}
fmt.Println(p.x)
fmt.Println(p.y)
}
package main
import "log"
func main() {
var langs [4]string
langs[0] = "Go"
langs[1] = "Python"
langs[2] = "Ruby"
langs[3] = "PHP"
if !(langs[0] == "Go") {
log.Fatal("Wrong string")
}
}
package main
import "fmt"
func main() {
langs := []string{"Go", "Python", "Ruby", "PHP"}
for _, e := range langs {
fmt.Println(e)
}
}
package main
import (
"fmt"
)
func main() {
m := make(map[string]string)
m["Go"] = "Beego"
m["Python"] = "Django"
m["Ruby"] = "Rails"
m["PHP"] = "Laravel"
for i := 0; i < 10; i++ {
for k, v := range m {
fmt.Println(fmt.Sprintf("%s: %s", k, v))
}
fmt.Println("")
}
}
package main
import (
"fmt"
)
type Point struct {
x float64
y float64
}
func main() {
p := new(Point)
p.x = 3.0
p.y = 4.0
fmt.Println(fmt.Sprintf("(%.2f, %.2f)", p.x, p.y))
}
package main
import (
"log"
"math"
)
type Point struct {
x float64
y float64
}
func NewPoint(x float64, y float64) *Point {
p := new(Point)
p.SetX(x)
p.SetY(y)
return p
}
func (p *Point) X() float64 {
return p.x
}
func (p *Point) Y() float64 {
return p.y
}
func (p *Point) SetX(x float64) {
p.x = x
}
func (p *Point) SetY(y float64) {
p.y = y
}
func Dist(p1 *Point, p2 *Point) float64 {
xSqr := math.Pow(p1.X()-p2.X(), 2)
ySqr := math.Pow(p1.Y()-p2.Y(), 2)
return math.Sqrt(xSqr + ySqr)
}
func main() {
p1 := NewPoint(0, 0)
p2 := NewPoint(3.0, 4.0)
if !(Dist(p1, p2) == 5.0) {
log.Fatal("Wrong value")
}
}
#GOROOT
export GOROOT=/usr/local/go
#GOPATH
export GOPATH=$HOME/Documents/go_workspace
#GOROOT bin
export PATH=$PATH:$GOROOT/bin
#GOPATH bin
export PATH=$PATH:$GOPATH/bin
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
package main
import (
"fmt" // printf
"html"
"log"
"net/http" // Package http provides HTTP client and server implementations
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
step by step refactor