GO 语言入门

google go: 入门
参考: http://www.infoq.com/articles/google-go-primer

特点: simple, fast, safe and concurrent

Variable Declarations

var sum int // Just a declaration
var total int = 42 // A declaration with initialization
name := "Samuel"

Conditionals

if result := someFunc(); result > 0 {
/* Do something */
} else {
/* Handle error */
}

Switches

var result int
switch byte {
case 'a', 'b':
  result = 1
default:
  result = 0
}

switch result := calculate(); true {
case result < 0:
  /* negative */
case result > 0:
  /* positive */
default:
  /* zero */
}

Range

range表达式右边必须是array, slice, string or map 类型, or a pointer to an array; or it may be a channel.

Functions

func add(a, b int) int { return a + b }

Multiple Return Values

func divide(a, b int) (quotient, remainder int) {
  quotient = a / b
  remainder = a % b
  return
}

Anonymous Functions 匿名函数(闭包)

func makeAdder(x int) (func(int) int) {
  return func(y int) int { return x + y }
}

func main() {
  add5 := makeAdder(5)
  add36 := makeAdder(36)
  fmt.Println("The answer:", add5(add36(1))) //=> The answer: 42
}
闭包可以做为参数传递

Primitive Types

两种新类型 two new types: slice and map.

Arrays不是动态的,跟c一样。
slices是一种新形式的array

/* Construct a slice on ary that starts at s and is len elements long */
s1 := ary[s:len]

/* Omit the length to create a slice to the end of ary */
s2 := ary[s:]

/* Slices behave just like arrays */
s[0] == ary[s] //=> true

// Changing the value in a slice changes it in the array
ary[s] = 1
s[0] = 42
ary[s] == 42 //=> true
改变slices的同时,也将改变array

/* Move the start of the slice forward by one, but do not move the end */
s2 = s2[1:]

/* Slices can only move forward */
s2 = s2[-1:] // this is a compile error

/* Cannot grow it past its capacity */
s = s[0:4] // this is a compile error

不需要array也能初始化slices

/* literal */
s1 := []int{1,2,3,4,5}

/* empty (all zero values) */
s2 := make([]int, 10) // cap(s2) == len(s2) == 10

Maps 哈希

m := make(map[string] int) // A mapping of strings to ints

/* Store some values */
m["foo"] = 42
m["bar"] = 30

/* Read, and exit program with a runtime error if key is not present. */
x := m["foo"]

/* Read, with comma-ok check; ok will be false if key was not present. */
x, ok := m["bar"]

/* Check for presence of key, _ means "I don't care about this value." */
_, ok := m["baz"] // ok == false

/* Assign zero as a valid value */
m["foo"] = 0;
_, ok := m["foo"] // ok == true

/* Delete a key */
m["bar"] = 0, false
_, ok := m["bar"] // ok == false

Object Orientation 面向对象

Structs

type Point struct {
  x, y float64
}

var p *Point = new(Point)
p.x = 3
p.y = 4
实例化个对象,并用指针类型的p去调用它的方法和变量
/* Note the receiver is *Point */
func (self *Point) Scale(factor float64) {
  self.x = self.x * factor
  self.y = self.y * factor
}
p.Scale(2);
d = p.Length() //=> 10
注意下面的self被定义成指针,这样self的值修改后可以返回修改后的值。如果定义成Point,参数是传值的,修改后的值不会被返回。

Interfaces 接口

duck-typed mentality 编译是动态识别类型

定义 type Writer interface {
  Write(p []byte) (n int, err os.Error)
}
type Frobber interface {
  Frob()
}

func frobtastic(f Frobber) { f.Frob() }
功能的抽象,作为参数可在别处调用

每个对象都实现了一个空接口 interface {}

Inheritance 继承

go语言没有继承, 使用组合和代理
type Engine interface {
  Start()
  Stop()
}

type Car struct {
  Engine
}
func GoToWorkIn(c Car) {
  /* get in car */

  c.Start();

  /* drive to work */

  c.Stop();

  /* get out of car */
}

也可以使用代理
type Base struct {}
func (Base) Magic() { fmt.Print("base magic") }
func (self Base) MoreMagic() {
  self.Magic()
  self.Magic()
}

type Foo struct {
  Base
}
func (Foo) Magic() { fmt.Print("foo magic") }
f := new(Foo)
f.Magic() //=> foo magic
f.MoreMagic() //=> base magic base magic

方法重载不对其有影响

Concurrency 并发

message-passing model  消息传送 支持内存共享
逻辑: 通信不依赖内存共享 内存共享依赖通信

两个基本结构: goroutines  channels

Goroutines
有不同名字, 可以卸载任何依赖包
定义 go DoThis() // but do not wait for it to complete
匿名函数调用  go func() {
  for { /* do something forever */ }
}() // Note that the function must be invoked

Channels

提供了FIFO先进先出的消息队列供并发间通信
/* Creating a channel uses make(), not new - it was also used for map creation */
ch := make(chan int)

/* Sending a value blocks until the value is read */
ch <- 4

/* Reading a value blocks until a value is available */
i := <-ch

长时间数值计算
ch := make(chan int)

go func() {
  result := 0
  for i := 0; i < 100000000; i++ {
    result = result + i
  }
  ch <- result
}()

/* Do something for a while */

sum := <-ch // This will block if the calculation is not done yet
fmt.Println("The sum is:", sum)

两个方法定制:
指定缓存大小
可发送接受操作成功信息
/* Create a channel with buffer size 5 */
ch := make(chan int, 5)

/* Send without blocking, ok will be true if value was buffered */
ok := ch <- 42

/* Read without blocking, ok will be true if a value was read */
val, ok := <-ch

Packages 包
文件开头 依赖包声明, 大写开头的能同时被其他包使用

package geometry

import "math"

/* Point is capitalized, so it is visible outside the package. */

type Point struct {

  /* the fields are not capitalized, so they are not visible
     outside of the package */

  x, y float64
}

总结

两个大的缺失: exceptions and generics(泛型), 目的是要取代C

猜你喜欢

转载自firemagic.iteye.com/blog/576701