Overview
Download
Development: vi emacs idea eclipse vs sublime
IDE: GoLand, liteIDE
Default GOPATH ~/go/src
Basic Syntax
Variable definition uses `var`. Variables defined outside functions can use parentheses.
package main
import "fmt"
//函数外定义要使用var
var aa=3
var ss="kkk"
var bb =true
//可以使用括号的方式
var (
cc int
dd string
ee bool
)
func variableZeroValue() {
var a int
var s string
fmt.Println("%d %q\n", a, s)
}
func variableInitialValue() {
var a, b int = 3, 4
var s string = "abc"
fmt.Println(a, b, s)
}
func variableTypeDedtection() {
var a, b, c, s = 2, 3, true, "def"
// 类型推断
fmt.Println(a, b, c, s)
}
//冒号定义
func variableShorter() {
//第一次
a, b, c, s := 2, 3, true, "def"
// 类型推断
fmt.Println(a, b, c, s)
}
func main() {
fmt.Println("hello world")
variableZeroValue()
variableInitialValue()
variableTypeDedtection()
variableShorter()
}
Built-in Types
boolstring(u)int(u)int8(u)int16(u)int32(u)int64uintptr(pointer)byte,rune(character, Go's `char` type, 32-bit)float32,float64,complex64,complex128(complex number type, real and imaginary parts)
Complex Numbers Review
- i = $\sqrt{-1}$
- Complex number: 3+4i
- $|x+y|$'s modulus = $\sqrt{3^2+4^2}$ = 5
- $i^2$=-1,$i^3$=-i,$i^4$=1,...
- $e^{i\phi}$ = cos$\phi$+isin$\phi$
e is the unit circle, $\phi$ is the angle of counter-clockwise rotation, as shown in the figure (Taylor series expansion)
- $e^{i\phi}$ = $\sqrt{cos^2\phi+sin^2\phi}$ = 1
- $e^{i\pi}$ = -1, $e^{i\frac{3}{2}\pi}$ = -i,$e^{i2\pi}$=1
- Deriving Euler's formula $e^{i\pi}$+1=0
Verifying with Go syntax
func euler(){
c:= 3+4i //表示复数
fmt.Println(cmplx.Abs(c))
//欧拉公式
fmt.Println(cmplx.Pow(math.E,1i*math.Pi)+1)
fmt.Println(cmplx.Exp(1i*math.Pi)+1)
}
Type Conversion
Go **only has explicit type conversion**
func triangle() {
var a, b int = 3, 4
var c int
c = int(math.Sqrt(float64(a*a + b*b)))
fmt.Println(c)
}
Constant Definition
func consts() {
const filename = "abc.txt"
const a, b = 3, 4
var c int
c = int(math.Sqrt(float64(a*a + b*b)))
fmt.Println(filename, c)
}
Enumerated Types
- Normal enumerated types
- Auto-incrementing enumerated types
func enums() {
const (
cpp = 0 //iota const是自增值
java = 1
python = 2
gloang = 3
)
// b,kb,mb,gb,tb,pb
const (
b = 1 << (10 * iota)
kb
mb
gb
tb
pb
)
}
Recap
- Variable type is written after the variable name
- Compiler can infer variable types
- No `char`, only `rune`
- Native support for complex number types
If
// 不需要括号的
package main
import (
"fmt"
"io/ioutil"
)
func main() {
const filename = "abc.txt"
contents,err:=ioutil.ReadFile(filename)
if err!=nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n",contents)
}
}
// 或者条件之前先赋个值用分号分隔
func main() {
const filename = "abc.txt"
//contents,err:=ioutil.ReadFile(filename)
if contents,err:=ioutil.ReadFile(filename); err!=nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n",contents)
}
}
Switch
// switch 没有break;
func switchFunc(a, b int, op string) int {
var result int
switch op {
case "+":
result = a + b
case "-":
result = a - b
case "*":
result = a * b
case "/":
if b == 0 {
fmt.Printf("%s\n", errors.New("除数为零"))
break
}
result = a / b
default:
fmt.Printf("not found operation")
}
return result
}
// 另外一种switch不写值,而在case中写条件判断
func grade(score int) string {
g := ""
switch {
case score<0 || score>100
panic(fmt.Sprintf("Wrong score: %d", score)) //中断程序执行
case score < 60:
g = "F"
case score < 80:
g = "C"
case score < 90:
g = "B"
case score <= 100:
g = "A"
}
return g
}
Switch statements automatically `break`, unless `fallthrough` is used
For
Intuitively, there are no parentheses
package main
import (
"fmt"
"strconv"
)
func convertToBin(n int) string {
result := ""
for ; n > 0; n /= 2 {
lsb := n % 2
result = strconv.Itoa(lsb) + result
}
return result
}
func main() {
fmt.Println(
convertToBin(5), //101
convertToBin(13), //1011--> 1101
)
// 调用时,返回值不有可以用_来点位
}
The increment condition can also be omitted
func printFile(filename string) {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
//相当于while
fmt.Println(scanner.Text())
}
}
//什么都不加就是死循环,因为并发编程时要用到gorutine
Functions
Function name comes first, return values come after. Return values can be multiple, and can be named; Typically, a function returns one value and an error. Function parameters can also be functions. It has no default parameters and has a variadic parameter list ...
package main
import (
"fmt"
"math"
"reflect"
"runtime"
)
func main() {
//div(13, 3)
fmt.Println(apply(pow, 2, 3))
fmt.Println(apply(func(i int, i2 int) int {
return int(math.Pow(float64(i), float64(i2)))
}, 3, 4))
fmt.Println("多参数和:", sum(1, 2, 3))
}
func divid(a,b int) (int,int){
var q,r int
q = a/b
r = a%b
return q,r
}
// 多个返回值,并指定名字
func div(a, b int) (q, r int) {
q = a / b
r = a % b
return
}
func pow(a, b int) int {
return int(math.Pow(float64(a), float64(b)))
}
// 参数传函数
func apply(op func(int, int) int, a, b int) int {
p := reflect.ValueOf(op).Pointer()
opName := runtime.FuncForPC(p).Name()
fmt.Printf("Calling function %s with args"+
"(%d,%d)\n", opName, a, b)
return op(a, b) //也可以使用匿名函数
}
// 可变参数
func sum(number ...int) int {
sum := 0
for _, v := range number {
sum += v
//fmt.Println(v)
}
return sum
}
Features
- Return type is written at the end
- Can return multiple values
- Functions can be passed as parameters
- No default parameters, variadic parameter list
Pointers
var a int=2
var pa *int = &a
*pa = 3
// 有指针,但指针不能运算
Go pass-by-value, pass-by-reference? **Go language only has pass-by-value**
// 没效果
func main(){
c, d := 2, 3
fmt.Printf("c=%v,d=%v\n", c, d)
swap(c, d)
fmt.Printf("\nswaped c=%v,d=%v\n", c, d)
}
// 值传递的,还是地址传递的说明
func swap(a, b int) {
a, b = b, a
}
// 解决一 swap参数为地址,调用时要传地址
func main(){
c, d := 2, 3
fmt.Printf("c=%v,d=%v\n", c, d)
swap(&c, &d)
fmt.Printf("\nswaped c=%v,d=%v\n", c, d)
}
// 值传递的,还是地址传递的说明
func swap(a, b *int) {
*a, *b = *b, *a //地址交换
}
// 解决二,返回新的数据
func swapv1(a,b int) (int,int){
return b,a
}
Arrays
func main() {
var arr1 [5]int
arr2:=[3]int{1,3,5}
arr3:=[...]int{2,4,6,8,10} //不写...就是切片了
fmt.Println(arr1,arr2,arr3)
// 遍历数据
for i := 0; i < len(arr3); i++ {
fmt.Println(arr3[i])
}
// 一般使用range来遍历 i是下标,v是值
for i, v := range arr3 {
fmt.Println(i, v)
}
// 最大值
maxi, maxv := MaxNumber(&arr3)
fmt.Printf("\nMax index %v value %v\n",maxi, maxv)
arr4:=[]int{1,3,5,7,9,11}
maxi, maxv := MaxNumberv1(&arr4)
fmt.Printf("\nMax index %v value %v\n",maxi, maxv)
}
// 求最大值
func MaxNumber(numbers *[5]int)(int,int){
maxi:=-1
maxValue:=-1
for i,v:=range numbers {
if v>maxValue {
maxi,maxValue = i,v
}
}
}
// 求最大值
func MaxNumberv1(numbers *[]int) (int, int) {
maxi := -1
maxValue := -1
for i, v := range *numbers {
if v > maxValue {
maxi, maxValue = i, v
}
}
return maxi, maxValue
}
**Arrays are value types** and must have a defined length
func printArray(arr [5]int) {
// 注意这个参数 [5]int 和 []int不是一回事儿
// 也可以*[5]int也可以传地址
for i,v:=range arr {
fmt.Println(i,v)
}
}
// main中调用时
printArray(arr3) //对的
printArray(arr4) //会报类型错误
printArray(arr1) //对的
printArray(arr2) //错的 因为长度对不上,认为是两种类型
Slices
Understand it as a view of an array
package main
import "fmt"
func main() {
arr := [...]int{1, 2, 3, 4, 5, 6, 7}
s := arr[2:6]
fmt.Println("arr=", arr)
fmt.Println("arr[2:6]=", s)
fmt.Println("arr[2:]=", arr[2:])
fmt.Println("arr[:6]=", arr[:6])
fmt.Println("arr[:]=", arr[:])
s1 := arr[2:]
s2 := arr[:]
fmt.Println("s1=", s1)
fmt.Println("s2=", s2)
fmt.Println("After updateSlice(s1)")
UpdateSlices(s1)
fmt.Println(s1)
fmt.Println(arr)
fmt.Println("After updateSlice(s2)")
UpdateSlices(s2)
fmt.Println(s2)
fmt.Println(arr)
}
func UpdateSlices(s []int) {
s[0] = 100
}
/*
arr= [1 2 3 4 5 6 7]
arr[2:6]= [3 4 5 6]
arr[2:]= [3 4 5 6 7]
arr[:6]= [1 2 3 4 5 6]
arr[:]= [1 2 3 4 5 6 7]
s1= [3 4 5 6 7]
s2= [1 2 3 4 5 6 7]
After updateSlice(s1)
[100 4 5 6 7]
[1 2 100 4 5 6 7]
After updateSlice(s2)
[100 2 100 4 5 6 7]
[100 2 100 4 5 6 7]
*/
Proving that a slice is a view of an array,
Reslice
fmt.Println("Reslice:")
s2=s2[:5]
s2=s2[2:]
fmt.Println("Reslice s2[:5] s2[2:]",s2)
s2[0] = 200
fmt.Println("arr", arr)
/*
Reslice:
Reslice s2[:5] s2[2:] [100 4 5]
arr [100 2 200 4 5 6 7]
它们都是不同的view array
*/
arr[0], arr[2] = 1, 2
s1 = arr[2:6]
s2 = s1[3:5]
fmt.Println("s1=", s1)
fmt.Println("s2=", s2)
/*
rr [100 2 200 4 5 6 7]
s1= [2 4 5 6]
s2= [6 7]
*/
Why can such values be retrieved? See the figure below, Slice index update diagram
As long as you don't exceed capacity
A slice can extend backward, but not forward. s[i] cannot exceed len(s). Extending backward cannot exceed the underlying array's cap(s)
arr[0], arr[2] = 1, 2
s1 = arr[2:6]
s2 = s1[3:5]
fmt.Printf("s1=%d,len(s1)=%d,cap(s1)=%v\n", s1, len(s1), cap(s1))
fmt.Printf("s2=%d,len(s2)=%d,cap(s2)=%v\n", s2, len(s2), cap(s2))
Continuously adding values to a slice
s3 := append(s2, 10)
s4 := append(s3, 11)
s5 := append(s4, 12)
fmt.Println("arr", arr)
fmt.Println("s3,s4,s5", s3, s4, s5)
s4, s5 are no longer the original `arr`. The system will allocate a new, longer array.
When adding elements, if `cap` is exceeded, the system will reallocate a larger underlying array. If the original array is still in use, it is retained; otherwise, it is garbage collected
package main
import "fmt"
func main() {
var s []int //zero value for slice is nil
for i := 0; i < 100; i++ {
printSlice(s)
s = append(s, 2*i+1)
}
fmt.Println(s)
s1:=[]int{2,4,6,8}
// 长度是16
s2:=make([]int,16)
s3:=make([]int,10,32)
}
func printSlice(s []int) {
fmt.Printf("len=%d,cap=%d\n", len(s), cap(s))
}
// 它每次都是乘以2
Declaring slices
s1:=[]int{2,4,6,8}
// 长度是16
s2:=make([]int,16)
s3:=make([]int,10,32)
fmt.Printf("s1=%v",s1)
fmt.Printf("s2=%v",s2)
fmt.Printf("s3=%v",s3)
copy(s2,s1)
copy(s2, s1)
fmt.Printf("copy(s2,s1)s2=%v\n", s2)
printSlice(s2)
Deleting slice elements
fmt.Println("Deleting elements from slice")
s2 = append(s2[:3], s2[4:]...)
fmt.Printf("copy(s2,s1)=>s2=%v\n", s2)
printSlice(s2)
Deleting from head or tail
// pop tail
fmt.Println("Popping from front")
front := s2[0]
s2 = s2[1:]
fmt.Println("front=", front)
printSlice(s2)
fmt.Println("Popping from back")
tail := s2[len(s2)-1]
s2 = s2[:len(s2)-1]
fmt.Println(tail)
printSlice(s2)
Maps
Definition
map[k]vmap[k1]map[k2]vcan be followed by curly braces for initialization
m := map[string]string{
"name": "ccmouse",
"course": "golang",
"site": "imooc",
"quality": "notabd",
}
fmt.Println(m)
m2 := make(map[string]int) // m2== empty map
var m3 map[string]int // m3==nil
fmt.Println(m, m2, m3)
// 遍历
for k, v := range m {
fmt.Println(k, v) //这是无序的
}
// 获取名字
fmt.Println("Getting values")
courseName := m["course"]
fmt.Println(courseName)
// 如果不存在它会取zero value 本例中就是空串
if courseName, ok := m["cs"]; ok {
fmt.Println(courseName)
} else {
fmt.Println("key does not exist")
}
//删除元素
fmt.Println("Deleteing values")
name, ok := m["name"]
fmt.Printf("Getting key='name' value=%v is %v\n", name, ok)
fmt.Println("Deleting...")
delete(m, "name")
name, ok = m["name"]
fmt.Printf("Getting key='name' value=%v is %v\n", name, ok)
- Creating
make(map[string]int) - Getting
m[key] - If key does not exist, the initial value (zero value) of the value type is retrieved
- Use
value,ok:=m[key]to check if key exists delete()to remove- `range` iteration is unordered; to sort, keys must be placed in a slice, sorted, and then output
- Maps use hash tables, keys must be comparable for equality
- All built-in types except `slice`, `map`, and `function` can be used as keys
- Struct types not containing the above fields can be used as keys
Example
Finding the longest substring without repeating characters abcabcbb-->abc
bbbbb->b
pwwkew->wke
For each character X
lastOccurred[x]does not exist, or `< start`, no operation neededlastOccurred[x]>=startupdate `start` to `x+1`- Update
lastOccurred[x], update `maxLength`
package main
import "fmt"
func nonRep(s string) int {
lastOccurred := make(map[byte]int) //将byte=>rune(支持中文)
start := 0
maxLength := 0
for i, ch := range []byte(s) { //将byte=>rune (支持中文)
if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
start = lastOccurred[ch] + 1
}
if i-start+1 > maxLength {
maxLength = i - start + 1
}
lastOccurred[ch] = i
}
return maxLength
}
func main() {
fmt.Println(nonRep("abcabcbb"))
}
The above example supports Chinese characters
将byte=>rune(支持中文)
主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/6729
