golang的一些试验小程序

前端之家收集整理的这篇文章主要介绍了golang的一些试验小程序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

golang的Map程序:

package main

import "fmt"

type e interface{}

func mult2(t e) e {
	switch t.(type) {
	case int:
		return t.(int) * 2
	case string:
		return t.(string) + t.(string)
	}

	return t
}

func add3(t e) e {
	switch t.(type) {
	case int:
		return t.(int) + t.(int) + t.(int)
	case string:
		return t.(string) + t.(string) + t.(string)
	}

	return t
}

func localmap(s []e,f func(e) e) {
	s2 := make([]e,len(s))
	for k,v := range s {
		s2[k] = f(v)
	}
	fmt.Println(s2)
}

func main() {
	slice1 := []e{1,2,3,4,"a","hello"}
	slice2 := []e{"a","b","c"}
	localmap(slice1,mult2)
	localmap(slice2,mult2)

	localmap(slice1,add3)
	localmap(slice2,add3)
}

运行结果:

[2 4 6 8 aa hellohello]
[aa bb cc]
[3 6 9 12 aaa hellohellohello]
[aaa bbb ccc]

要分清数组指针类型 *[n]T和指针数组类型 [n]*T。用new创建数组,返回的是数组指针:

package main
import "fmt"

func test(a *[10]int) {
	a[2] = 100
}
func main() {
	var a = new([10]int)
	test(a)
	fmt.Println(a,len(a))
}

golang的OOP示例:

package main

import "fmt"

type User struct {
	Id   int
	Name string
}

type Manager struct {
	User
	Group string
}

type Tester interface {
	Test()
}

func (this *User) Test() {
	fmt.Println(this)
}

func (this *Manager) Test() {
	fmt.Println(this)
}

func dosometing(o Tester) {
	o.Test()
}

func main() {
	m := Manager{User: User{2,"jack"},Group: "IT"}
	dosometing(&m)
	dosometing(&m.User)
}

拥有超集的接口可以被转换为子集的接口:

package main

import "fmt"

type User struct {
	Id   int
	Name string
}

type Manager struct {
	Group string
	User
}

type IUser interface {
	Test()
}

type IManager interface {
	Test()
	Test2()
}

func (this *User) Test() {
	fmt.Println(this)
}

func (this *Manager) Test2() {
	fmt.Println(this)
}

func main() {
	var im IManager = &Manager{"IT",User{1,"tom"}}
	im.Test()
	im.Test2()

	var iu IUser = im
	iu.Test()
}

对于channel,首先要明确“发送(send)”与“接收(receive)”的概念:“发送是指”值传递给channel;“接收”是指从channel读取值。可以定义仅能发送或仅能接收的单向channel。比如c1 chan<-int,仅能发送int类型的值给c1;c2 <-chan int,c2仅能接收int类型的值。示例如下:

package main

import (
	"fmt"
)

func recv(i <-chan int,o chan<- bool) {
	for v := range i {
		fmt.Println(v)
	}
	o <- true
}

func send(i chan<- int) {
	for j := 0; j < 10; j++ {
		i <- j
	}
	close(i)
}

func main() {
	i := make(chan int)
	o := make(chan bool)
	go recv(i,o)
	go send(i)
	<-o
}

使用channel实现信号量:

package main

import (
	"fmt"
	"sync"
	"time"
)

var sem = make(chan int,2)
var wg = sync.WaitGroup{}

func worker(i int) {
	sem <- 1
	fmt.Println(time.Now().Format("04:05"),i)
	time.Sleep(1 * time.Second)
	<-sem
	wg.Done()
}

func main() {
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go worker(i)
	}
	wg.Wait()
}

猜你在找的Go相关文章