go语言1小时——从不会到入门

磨刀不误砍柴工——go语言学习必备资料:
1. go 下载安装
2. 官方文档 Effective go
3. 官方文档中文翻译pdf下载
4. 国人写的go IDE——LiteIDE 32.1

本文原文地址:http://blog.csdn.net/caib1109/article/details/75578974
第一步——Hello world

// testDemo project main.go
package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello World!")
}

第二步——项目结构
go install和go build之争。目前,IDEA插件和LiteIDE都采用了go build。Eclipse插件采用了go install。官方推荐go install方式编译项目,官方项目结构应该是

项目名称
  |--bi
  |--pkg
  +--src

第三步——package main、func main() { }、func init() { }

一图胜千言

这里写图片描述

第四步——go语言面向对象

// File Name: main.go
package main

import (
    "fmt"
)

type Human interface {
    Talk()
}
type Person struct {
    name  string
    Human // Person is-a Human
}

func (p *Person) Talk() {
    fmt.Println("Hi, my name is", p.name)
}

type Citizen struct {
    country string
    person  Person
    Human   //B is-a A
}

func (c *Citizen) Talk() {
    fmt.Println("Hi, my name is", c.person.name)
}

func SpeakTo(h Human) {
    h.Talk()
}

func main() {
    p := Person{name: "Dave"}
    c := Citizen{person: Person{name: "Steve"}, country: "America"}

    SpeakTo(&p)
    SpeakTo(&c)
}

第五步——go语言并发

// File Name: main.go
package main

import (
    "fmt"
)

var ch = make(chan string)

func message() {
    msg := <-ch
    fmt.Println(msg)
}

func main() {
    go message()
    ch <- "Hello,CSP."
}

拓展阅读:
[1] go语言的面向对象、接口、伪多态和真多态

猜你喜欢

转载自blog.csdn.net/caib1109/article/details/75578974
今日推荐