GoLang之”奇怪用法“实践总结

本文探讨了Go语言的一些不寻常的特性,如变量声明顺序、package组织方式、可见性规则、内置关键字、函数定义、隐式变量声明、UTF-8编码、big.Int的使用注意事项、循环结构、自增运算符、slice操作、匿名函数和闭包等。通过代码实践,深入理解Go语言的独特之处。
摘要由CSDN通过智能技术生成

2013-11-23 wcdj

0 摘要


本文通过对A Tour of Go的实践,总结Go语言的基础用法。

 

1 Go语言”奇怪用法“有哪些?


1,go的变量声明顺序是:”先写变量名,再写类型名“,此与C/C++的语法孰优孰劣,可见下文解释:
http://blog.golang.org/gos-declaration-syntax

2,go是通过package来组织的(与python类似),只有package名为main的包可以包含main函数,一个可执行程序有且仅有一个main包,通过import关键字来导入其他非main包。

3,可见性规则。go语言中,使用大小写来决定该常量、变量、类型、接口、结构或函数是否可以被外部包含调用。根据约定,函数名首字母小写即为private,函数名首字母大写即为public。

4,go内置关键字(25个均为小写)。

5,函数不用先声明,即可使用。

6,在函数内部可以通过 := 隐士定义变量。(函数外必须显示使用var定义变量)

7,go程序使用UTF-8编码的纯Unicode文本编写。

8,使用big.Int的陷阱:
http://stackoverflow.com/questions/11270547/go-big-int-factorial-with-recursion

9,从技术层面讲,go语言的语句是以分号分隔的,但这些是由编译器自动添加的,不用手动输入,除非需要在同一行中写入多个语句。没有分号及只需少量的逗号和圆括号,使得go语言的程序更容易阅读。

10,go语言只有一个循环结构——for循环。

11,go里的自增运算符只有——“后++”

12,go语言中的slice用法类似python中数组,关于slice的详细用法可见:http://blog.golang.org/go-slices-usage-and-internals

13,函数也是一个值,使用匿名函数返回一个值。

14,函数闭包的使用,闭包是一个匿名函数值,会引用到其外部的变量。



2 代码实践


/* gerryyang
 * 2013-11-23
 */

package main

import (
    "fmt"
    "math"
    "math/big"
    "math/cmplx"
    "math/rand"
    "net/http"
    "os"
    "runtime"
    "time"
)

// Outside a function, every construct begins with a keyword (var, func, and so on) and the := construct is not available
// The var statement declares a list of variables; as in function argument lists, the type is last
var x, y, z int
var c, python, java bool

// A var declaration can include initializers, one per variable
var x1, y1, z1 int = 1, 2, 3

// If an initializer is present, the type can be omitted; the variable will take the type of the initializer
var c1, python1, java1 = true, false, "no!"

// basic types
// bool
// string
// int int8 int16 int32 int64
// uint uint8 uint16 uint32 uint64 uintptr
// byte (alias for uint8)
// rune (alias for int32, represents a Unicode code point)
// float32 float64
// complex64 complex128
var (
    ToBe    bool       = false
    MaxInt  uint64     = 1<<64 - 1
    complex complex128 = cmplx.Sqrt(-5 + 12i)
)

// Constants are declared like variables, but with the const keyword
const Pi = 3.14

// Constants can be character, string, boolean, or numeric values
const World = "世界"

// Numeric Constants
const (
    Big   = 1 << 100
    Small = Big >> 99 // 2
)

type Vertex struct {
    X
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值