Go语言先睹为快

delphidoc 2009-12-18
转载自:http://www.cnblogs.com/niuchenglei/archive/2009/11/16/1604118.html

20091110日,就在这个光棍节的前一天,我们伟大的Google为了不让我们这些单身可怜的程序员们在光棍节那天空守寂寞,特意推出了Go语言,我猜意思是Why don't your courtship to a sweetheart?go,go,go……

哈哈,上面的内容纯属虚构,如有雷同纯属巧合。下面进入正题Go,Go,Go

Introduction

Go语言是一门动态的编译性语言,是一种类CC++语言,它简单、快速、安全,速度比python还快,而且开源。

进入HelloWorld

05    package main


07    import fmt "fmt"  // Package implementing formatted I/O.



09    func main() {

10        fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n");

11    }

每一个源文件都包含一个package属性,用来标注代码所属的包,跟C#namespace类似。而import则是引入包,同C#using。函数则是用func关键词。


Compiling

Go
语言的编译器有2个编译器,gccgo和不同架构下的编译器,有6g/8g分别代表64位和32位编译器。下面看编译的代码:

6g
编译器使用:

    $ 6g helloworld.go  # compile; object goes into helloworld.6

    $ 6l helloworld.6   # link; output goes into 6.out

    $ 6.out

    Hello, world; or Καλημέρα κόσμε; or こんにちは 世界

    $

gccgo编译器使用:

    $ gccgo helloworld.go

    $ a.out

    Hello, world; or Καλημέρα κόσμε; or こんにちは 世界

    $

 


Echo

下面看一大段Go代码,来通过代码了解语言特性。

05    package main


07    import (

08        "os";

09        "flag";  // command line option parser

10    )



12    var omitNewline = flag.Bool("n", false, "don't print final newline")



14    const (

15        Space = " ";

16        Newline = "\n";

17    )



19    func main() {

20        flag.Parse();   // Scans the arg list and sets up flags

21        var s string = "";

22        for i := 0; i < flag.NArg(); i++ {

23            if i > 0 {

24                s += Space

25            }

26            s += flag.Arg(i);

27        }

28        if !*omitNewline {

29            s += Newline

30        }

31        os.Stdout.WriteString(s);

32    }

从上面的代码中我们发现:


1.Go
语言可以使用一个关键词+多个谓词。比如import可以引入多个packageconst可以定义多个常变量。

2.Go
语言的;号是可以省略的,但在有些时候是不能省略的。81521行的分号是不能省略的,9162631行的分号是可以省略的。

3.
它的for语句有点变化,省略掉了括号。

4.
声明变量的方式不惟一,var关键词、var关键词与类型一起使用(21行)、:=运算符。:=运算符是给初始化变量赋值的运算符


Types
类型

Go
语言支持丰富的数据类型,有int,float,int8,int32,int64,uint,uint32,float64,string,byte,bool等。

同时它对字符串的操作也是丰富的

11        s := "hello";

12        if s[1] != 'e' { os.Exit(1) }

13        s = "good bye";

14        var p *string = &s;

15        *p = "go";

数组的声明的形式为:

var arrayOfInt [10]int;

它还支持字典类型:

m := map[string]int{"one":1 , "two":2}

Allocation分配(new一个对象)

Go语言可以使用new关键词分配一个对象,它返回对象的指针

    type T struct { a, b int }

    var t *T = new(T);

当然可以更简单些:

    t := new(T);

 

今天先到这里了,没有把文档看完.期待Go可以给我们更多的精彩,Just Go

 

 

 

Global site tag (gtag.js) - Google Analytics