go学习笔记(02)-基本语法-包与可见性

基本语法

基本结构

包的基本结构如下

//程序运行的入口是包 `main`。
package main

//导入包"fmt"和"math/rand"
import (
	"fmt"
	"math/rand"
)

//或
import std "fmt"	//指定别名
import "math"

// 常量的定义
const PI = 3.14

// 全局变量的声明与赋值
var name = "gopher"

// 一般类型声明
type newType int

// 结构的声明
type gopher struct{}

// 接口的声明
type golang interface{}

// 函数的声明
func add(x int,y int) int{
	return x + y
}
// 当两个或多个连续的函数命名参数是同一类型,则除了最后一个类型之外,其他都可以省略。
func add2(x, y int) int{
	return x + y
}

// 由 main 函数作为程序入口点启动
func main() {
	fmt.Println("My favorite number is", rand.Intn(10))
    fmt.Println(add(42,13)
}

别名

导入包时的同时可以指定别名

import std "fmt"

定义别名时可以通过如下方法调用

std.Println("Hello world!你好,世界!")

注意,定义别名后就不能通过原来的名字进行调用

可见性规则

Go使用大小写来决定常量,变量,类型等是否可以被外部调用

根据约定,函数名首字母小写为Private,大写为Public,针对的可见性为包级别

posted @ 2015-01-31 21:40  doitNow  阅读(293)  评论(0编辑  收藏  举报