安装
$ apt-get install bison ed gawk libc6-dev mercurial python-setuptools python-dev build-essential $ hg clone -r release https://go.googlecode.com/hg/ go $ export GOROOT=$HOME/go $ export GOARCH=amd64 $ export GOOS=linux $ export GOTOOL=$HOME/go/pkg/tool/linux_amd64/ $ export PATH=.:$PATH:$GOBIN:$GOTOOL $ cd go/src $ ./all.bash
更新go版本
$ cd $GOROOT && hg identify $ hg pull && hg update release $ ./all.bash
Workspace sample
bin/ todo # command executable pkg/ linux_amd64/ code.google.com/p/goauth2/ oauth.a # package object github.com/nf/todo/ task.a src/ code.google.com/p/goauth2/ .hg/ # mercurial repository metadata oauth/ oauth.go # package source oauth_test.go # test source github.com/nf/ todo/ .git/ task/ task.go # package source todo.go
hello, world
示例1:
package main import "fmt" func main() { fmt.Printf("hello, world\n") } $ 6g helloworld.go $ 6l helloworld.6 $ ./6.out 或者 $ go run helloworld.go
示例2:
$HOME/HelloWorldWorkspace/ bin/ helloworld # after go install pkg/ src/ github.com/msolo/helloworld .git helloworld.go $ export GOPATH=$HOME/HelloWorldWorkspace $ go install github.com/msolo/helloworld $ $GOPATH/bin/helloworld
示例:使用自定义包/库
package main import ( "fmt" "github.com/user/newmath" ) func main() { fmt.Printf("Hello, world. Sqrt(2) = %v\n", newmath.Sqrt(2)) }
package newmath // Sqrt returns an approximation to the square root of x. func Sqrt(x float64) float64 { z := 1.0 for i := 0; i < 1000; i++ { z -= (z*z - x) / (2 * z) } return z }
$HOME/HelloWorldWorkspace/ bin/ helloworld pkg/ linux_amd64/ # reflect your OS and architecture github.com/user/ newmath.a # package object src/ github.com/user/helloworld helloworld.go github.com/user/newmath sqrt.go $ go install github.com/user/helloworld
godoc
$ go get -v code.google.com/p/go.tools/cmd/godoc $ godoc -http=:8888 -goroot=$GOROOT $ godoc fmt Printf $ godoc –src fmt Printf
不论编写任何大小的注释,都要记得,第一句话将出现在 godoc 的 package list中。
紧接着下一行的文本被认为是同一段的;你必须空出一行来分隔段落。
预格式化文本必须在注释符号内缩进
以”BUG(who)”开头的顶级注释会被识别为已知的bug,会被包含在包文档的”Bugs”部分。”who”应当是能提供更进一步信息的用户的名字。
SourceCode format
$ gofmt –w program.go
基础知识
import
import "fmt" import "os" import "fmt"; import "os" import fm "fmt" import ( fm "fmt" "os" )
func init() { // code } // every package run first
声明
const str = "str" var identifier int (= 5) name := "Jack" a, b, c := 5, 7, "abc" var a float = 5.2 b := int(a) // b := int32(a) type ( IZ int STR string ) var a IZ = 5 const ( Sunday = iota // Sunday = 0 Monday // 1 ... ) var ( a int b bool ) var ( a = 15 b = false )
visibility rule
var Identifier1 string // this "object" is said to be exported var identifier2 string // not visible, like private
print
fmt.Print("Hello:", 23) str := "World!" fmt.Println("Hello", str)
fmt.Printf() && fmt.Sprintf() %v the value in a default format. when printing structs, the plus flag (%+v) adds field names %T a Go-syntax representation of the type of the value %t the word true or false %c the character represented by the corresponding Unicode code %x base 16, with lower-case letters for a-f %U Unicode format: U+1234; same as “U+%04X” %g whichever of %e or %f produces more compact output |
control statement
if initialization; condition { // code } else { // code } |
if val := 10; val > max { // do something } |
switch var1 { case val1: ... case val2: ... default: ... } |
switch var1 { case val1: ... case val2: fallthrough case val3: ... } |
for i := 0; i < 10; i++ { ... } for i >= 0 { // code } |
for pos, cha := range str { ... } |
string
rawString := `This is a raw string\n` // raw string: ` (反引号) str := "Hello," + "world" // str += "world!"
func Contains(s, substr string) bool func ContainsRune(s string, r rune) bool func Count(s, sep string) int func Join(a []string, sep string) string func Fields(s string) []string func FieldsFunc(s string, f func(rune) bool) []string func Index(s, sep string) int func LastIndex(s, sep string) int func IndexFunc(s string, f func(rune) bool) int func IndexRune(s string, r rune) int func HasPrefix(s, prefix string) bool func HasSuffix(s, suffix string) bool func Repeat(s string, count int) string func Replace(s, old, new string, n int) string func Split(s, sep string) []string func Title(s string) string // first Letter uppercase func ToTitle // all uppercase func ToLower func Trim(s string, cutset string) string func TrimLeft(s string, cutset string) string func TrimPrefix(s, prefix string) string |
strconv
func Atoi(s string) (i int, err error) func Itoa(i int) string // accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False func ParseBool(str string) (value bool, err error) // 解析小数点后6位,不能带其它字符 func ParseFloat(s string, bitSize int) (f float64, err error) func ParseInt(s string, base int, bitSize int) (i int64, err error) |
time、date
const ( ANSIC = "Mon Jan _2 15:04:05 2006" UnixDate = "Mon Jan _2 15:04:05 MST 2006" RubyDate = "Mon Jan 02 15:04:05 -0700 2006" RFC822 = "02 Jan 06 15:04 MST" // RFC822 RFC822Z = "02 Jan 06 15:04 -0700" // with zone RFC850 = "Monday, 02-Jan-06 15:04:05 MST" RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST" RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 RFC3339 = "2006-01-02T15:04:05Z07:00" RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00" Kitchen = "3:04PM" Stamp = "Jan _2 15:04:05" StampMilli = "Jan _2 15:04:05.000" StampMicro = "Jan _2 15:04:05.000000" StampNano = "Jan _2 15:04:05.000000000" ) const ( Nanosecond Duration = 1 Microsecond = 1000 * Nanosecond Millisecond = 1000 * Microsecond Second = 1000 * Millisecond ... ) const ( January Month = 1 + iota ... ) const ( // type Weekday Sunday Weekday = iota ... )
func Sleep(d Duration) func After(d Duration) <-chan Time func Since(t Time) Duration func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time func Parse(layout, value string) (Time, error) func (t Time) Format(layout string) string func (t Time) Add(d Duration) Time func (t Time) AddDate(years int, months int, days int) Time func (t Time) Clock() (hour, min, sec int) func (t Time) Date() (year int, month Month, day int) func (Time) ISOWeek // range : 1 ~ 53 func (d Weekday) String() string
const shortForm = "2006-Jan-02" t, _ = time.Parse(shortForm, "2013-Feb-03") AddDate(-1, 2, 3) // applied to January 1, 2011: March 4, 2010.
functions :Normal, Lambda, Method
func greeting() { println(“In greeting: Hi!!!”) } g := func(i int) { fmt.Printf(“%d\n”, i) }
type binOp func(int, int) (int, int, int) someFunc := binOp
func getX2AndX3_2(input int) (x2 int, x3 int) { // 命名返回值 ... }
func min(a ...int) int { ... } arr := []int{7, 9, 3, 5, 1} x := min(arr...) // x := min(7, 9, 3, 5, 1)
func(x, y int) int { return x + y }(3, 4)
func main() { printHeader() defer printFooter() // 多个defer工作方式: 后进先出 }
Built-in function : len, cap, new, make, copy, append, panic, recover |
array
var arr1 [5]int // len(arr1) is 5 var arrAge = [5]int{18, 20, 15, 22, 16} var arrLazy1 = [...]int{5, 6, 7, 8, 22} var arrLazy2 = []int{5, 6, 7, 8, 22} var arrKeyValue1 = [5]string{3: "Chris", 4: "Ron"} var arrKeyValue2 = []string{3: "Chris", 4: "Ron"}
var slice1 []type = arr1[start:end] var slice2 []type = arr1[:] // var slice2 []type = arr1[0:len(arr1)] // var slice2 []type = &arr1 slice1 = slice1[:len(slice1)-1]
var slice1 []type = make([]type, len, cap) var slice2 []int = make([]int, 10) s1 := s1[0:len(s1)+1] s1_from := []int{1, 2, 3} s1_to := make([]int, 10) n := copy(s1_to, s1_from) // [1 2 3 0 0 ... 0] s13 := []int{1, 2, 3} s13 = append(s13, 4, 5, 6) // [1 2 3 4 5 6]
import "sort" sort.Ints(arr1) sort.IntsAreSorted(arr1) sort.Float64s(arr2) func SearchStrings(a []string, x string) int func Strings(a []string) // sorts a slice in increasing order
//Warning: as long as the slice is referred to, the full array will be kept in memory until it is no longer referenced.
map
var mapVar map[string]int map1 := make(map[string]float) map2 := map[string]float{} mf := map[int]func() int { 1: func() int { return 10 }, 5: func() int { return 50 }, } delete(map1, key1)
regexp
ok, _ := regexp.Match(pat, []byte(searchIn)) ok, _ := regexp.MatchString(pat, searchIn) func Compile(expr string) (*Regexp, error) re := regexp.MustCompile(“fo.?”) fmt.Printf(“%q\n”, re.FindString(“seafood”)) // "foo" func (re *Regexp) Split(s string, n int) []string s := regexp.MustCompile(“a*”).Split(“abaabaccadaaae”, 5)
searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18" pat := "[0-9]+.[0-9]+" f := func(s string) string { v, _ := strconv.ParseFloat(s, 32) return strconv.FormatFloat(v * 2, 'f', 2, 32) } re, _ := regexp.Compile(pat) str1 := re.ReplaceAllString(searchIn, "##.#") str2 := re.ReplaceAllStringFunc(searchIn, f)
structs and methods
type struct1 struct { i1 int f1 float32 str string } func main() { ms := new(struct1) // ms := &struct1{10, 15.5, "Chris"} ms.i1 = 10 // var mt struct1 ms.f1 = 15.5 // mt = struct1{10, 15.5, "Chris"} ms.str = "Chris" }
// a Go method is a function that acts on variable of a certain type, called the receiver. type B struct { thing int } func (b *B) write() string { return fmt.Sprint(b) }
type camera struct { } func (c *camera) TakeAPicture() string { return “click” } type phone struct { } func (p *phone) Call() string { return "Ring Ring" } type cameraPhone struct { camera phone }
有疑问加站长微信联系(非本文作者)