• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

go语言练习

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 1 // main
 2 package main
 3 
 4 import (
 5     "fmt"
 6     "runtime"
 7     "sync"
 8 )
 9 
10 func main() {
11     fmt.Println("Hello World!")
12     runtime.GOMAXPROCS(1)
13     var wg sync.WaitGroup
14     wg.Add(2)
15     i := 999
16     fmt.Println("Start Goroutines")
17 
18     go func() {
19         defer wg.Done()
20         //共享变量 i wg
21         fmt.Println(i)
22         for count := 0; count < 3; count++ {
23             for char := 'a'; char < 'a'+26; char++ {
24                 fmt.Printf("%c ", char)
25             }
26         }
27     }()
28 
29     go func() {
30         defer wg.Done()
31         fmt.Println(i)
32         for count := 0; count < 3; count++ {
33             for char := 'A'; char < 'A'+26; char++ {
34                 fmt.Printf("%c ", char)
35             }
36         }
37     }()
38 
39     fmt.Println("Waiting to Finish")
40     wg.Wait()
41 
42     fmt.Println("\nTerminating Program")
43 }
View Code

go 协程练习

 

 

接口练习

 1 // Sample program to show what happens when the outer and inner
 2 // type implement the same interface.
 3 package main
 4 
 5 import (
 6     "fmt"
 7 )
 8 
 9 // notifier is an interface that defined notification
10 // type behavior.
11 type notifier interface {
12     notify()
13 }
14 
15 // user defines a user in the program.
16 type user struct {
17     name  string
18     email string
19 }
20 
21 // notify implements a method that can be called via
22 // a value of type user.
23 func (u *user) notify() {
24     fmt.Printf("Sending user email to %s<%s>\n",
25         u.name,
26         u.email)
27 }
28 
29 // admin represents an admin user with privileges.
30 type admin struct {
31     user
32     level string
33 }
34 
35 // notify implements a method that can be called via
36 // a value of type Admin.
37 func (a *admin) notify() {
38     fmt.Printf("Sending admin email to %s<%s>\n",
39         a.name,
40         a.email)
41 }
42 
43 // main is the entry point for the application.
44 func main() {
45     // Create an admin user.
46     ad := admin{
47         user: user{
48             name:  "john smith",
49             email: "[email protected]",
50         },
51         level: "super",
52     }
53 
54     // Send the admin user a notification.
55     // The embedded inner type's implementation of the
56     // interface is NOT "promoted" to the outer type.
57     sendNotification(&ad)
58 
59     // We can access the inner type's method directly.
60     ad.user.notify()
61 
62     // The inner type's method is NOT promoted.
63     ad.notify()
64 }
65 
66 // sendNotification accepts values that implement the notifier
67 // interface and sends notifications.
68 func sendNotification(n notifier) {
69     n.notify()
70 }
View Code

 

work代码注释 《go语言编程实战》

 1 package work
 2 
 3 import "sync"
 4 
 5 //接口
 6 type Worker interface {
 7     Task()
 8 }
 9 
10 //pool结构体
11 type Pool struct {
12     work chan Worker
13     wg   sync.WaitGroup
14 }
15 
16 //new函数  返回 pool指针
17 func New(maxGorountines int) *Pool {
18     p := Pool{
19         work: make(chan Worker),
20     }
21     //wg添加wait数量
22     p.wg.Add(maxGorountines)
23     for i := 0; i < maxGorountines; i++ {
24         go func() {
25             //执行POOL内的任务 完成后wg执行done
26             for w := range p.work {
27                 w.Task()
28             }
29             p.wg.Done()
30         }()
31     }
32 
33     return &p
34 }
35 
36 //将任务放入POOL
37 func (p *Pool) Run(w Worker) {
38     p.work <- w
39 }
40 
41 //关闭POOL
42 func (p *Pool) Shutdown() {
43     close(p.work)
44     p.wg.Wait()
45 }
View Code
 1 // main
 2 package main
 3 
 4 import (
 5     "fmt"
 6     "log"
 7     "sync"
 8     "time"
 9     "work"
10 )
11 
12 var names = []string{
13     "steve",
14     "bob",
15     "mary",
16     "therese",
17     "jason",
18 }
19 
20 type namePrinter struct {
21     name string
22 }
23 
24 func (m *namePrinter) Task() {
25     log.Println(m.name)
26     time.Sleep(time.Second)
27 }
28 
29 func main() {
30     fmt.Println("Hello World!")
31     p := work.New(2)
32 
33     var wg sync.WaitGroup
34     wg.Add(100 * len(names))
35 
36     for i := 0; i < 100; i++ {
37         for _, name := range names {
38             np := namePrinter{
39                 name: name,
40             }
41             go func() {
42                 p.Run(&np)
43                 wg.Done()
44             }()
45         }
46     }
47     wg.Wait()
48     p.Shutdown()
49 }
View Code

 

runner代码注释 《go语言编程实战》

 1 // runner
 2 package runner
 3 
 4 import (
 5     "errors"
 6     "fmt"
 7     "os"
 8     "os/signal"
 9     "time"
10 )
11 
12 //runner结构体
13 type Runner struct {
14     interrupt chan os.Signal
15     complete  chan error
16     timeout   <-chan time.Time
17     tasks     []func(int)
18 }
19 
20 //错误变量1
21 var Errtimeout = errors.New("received timeout")
22 //错误变量2
23 var ErrInterrupt = errors.New("received interrupt")
24 
25 //runner的new函数
26 func New(d time.Duration) *Runner {
27     return &Runner{
28         interrupt: make(chan os.Signal, 1),
29         complete:  make(chan error),
30         timeout:   time.After(d),
31     }
32 }
33 
34 //func(int)加入 runner
35 func (r *Runner) Add(tasks ...func(int)) {
36     r.tasks = append(r.tasks, tasks...)
37 }
38 
39 
40 //goroutine执行 结果超时或者错误 成功
41 func (r *Runner) Start() error {
42     signal.Notify(r.interrupt, os.Interrupt)
43 
44     go func() {
45         r.complete <- r.run()
46     }()
47 
48     select {
49     case err := <-r.complete:
50         return err
51     case <-r.timeout:
52         return Errtimeout
53     }
54 }
55 
56 //run函数 遍历函数数组
57 //若发生错误中断则返回 中断错误
58 func (r *Runner) run() error {
59     for id, task := range r.tasks {
60         if r.gotInterrupt() {
61             return ErrInterrupt
62         }
63         task(id)
64     }
65     return nil
66 }
67 
68 //通过interrupt接受中断
69 func (r *Runner) gotInterrupt() bool {
70     select {
71     case <-r.interrupt:
72         signal.Stop(r.interrupt)
73         return true
74     default:
75         return false
76     }
77 }
78 
79 
80 //无用main函数
81 func main() {
82     fmt.Println("Hello World!")
83 
84 }
View Code
 1 // main
 2 package main
 3 
 4 import (
 5     "fmt"
 6     "log"
 7     "os"
 8     "runner"
 9     "time"
10 )
11 
12 const timeout = 3 * time.Second
13 
14 func main() {
15     fmt.Println("Hello World!")
16     log.Println("Starting work.")
17 
18     r := runner.New(timeout)
19 
20     r.Add(createTask(), createTask(), createTask())
21 
22     if err := r.Start(); err != nil {
23         switch err {
24         case runner.Errtimeout:
25             log.Println("Terminating due to timeout")
26             os.Exit(1)
27         case runner.ErrInterrupt:
28             log.Println("Terminating due to interrupt")
29             os.Exit(2)
30         }
31     }
32     log.Println("Process ended")
33 }
34 
35 func createTask() func(int) {
36     return func(id int) {
37         log.Printf("processor - Task #%d", id)
38         time.Sleep(time.Duration(id) * time.Second)
39     }
40 }
View Code

 

go语言编程 代码修改

 1 package library
 2 
 3 //music 记录
 4 type MusicEntry struct {
 5     Id string
 6     Name string
 7     Artist string
 8     Source string
 9     Type string
10 }
musicentry
 1 package library
 2 
 3 import "errors"
 4 
 5 //音乐管理器  音乐记录数组
 6 type MusicManager struct {
 7     musics []MusicEntry
 8 }
 9 
10 //返回音乐管理器指针
11 func NewMusicManager() *MusicManager {
12     return &MusicManager{make([]MusicEntry, 0)}
13 }
14 
15 //返回音乐管理器 音乐数组的元素数
16 func (m *MusicManager) Len() int {
17     return len(m.musics)
18 }
19 
20 //输入索引 获取音乐记录指针
21 func (m *MusicManager) Get(index int) (music *MusicEntry, err error) {
22     if index < 0 || index >= len(m.musics) {
23         return nil, errors.New("Index out of range.")
24     }
25     return &m.musics[index], nil
26 }
27 
28 
29 //根据名字字符串 查找音乐记录的指针
30 func (m *MusicManager) Find(name string) *MusicEntry {
31     if len(m.musics) == 0 {
32         return nil
33     }
34 
35     for _, m := range m.musics {
36         if m.Name == name {
37             return &m
38         }
39     }
40     return nil
41 }
42 
43 //添加音乐记录  输入音乐记录指针
44 func (m *MusicManager) Add(music *MusicEntry) {
45 
46     m.musics = append(m.musics, *music)
47 }
48 
49 
50 //输入索引 移除指定索引 返回音乐记录指针
51 func (m *MusicManager) Remove(index int) *MusicEntry {
52     if index < 0 || index >= len(m.musics) {
53         return nil
54     }
55 
56     removedMusic := &m.musics[index]
57 
58     // Remove the found item from the slice.
59     if index < len(m.musics)-1 { // Element between first and last
60         m.musics = append(m.musics[:index-1], m.musics[index+1:]...)
61     } else if index == 0 { // empty it.
62         m.musics = make([]MusicEntry, 0)
63     } else { // The last element
64         m.musics = m.musics[:index-1]
65     }
66 
67     return removedMusic
68 }
69 
70 
71 
72 //输入名字字符串 移除符合的音乐记录  返回音乐记录指针
73 func (m *MusicManager) RemoveByName(name string) *MusicEntry {
74     if len(m.musics) == 0 {
75         return nil
76     }
77 
78     for i, v := range m.musics {
79         if v.Name == name {
80             return m.Remove(i)
81         }
82     }
83     return nil
84 }
manager
 1 package library
 2 
 3 import "testing"
 4 
 5 func TestOps(t *testing.T) {
 6     mm := NewMusicManager()
 7     if mm == nil {
 8         t.Error("NewMusicManager failed")
 9     }
10 
11     if mm.Len() != 0 {
12         t.Error("NewMusicManager failed,not empty")
13     }
14 
15     m0 := &MusicEntry{"1", "MyHeart", "Celion", "http://wwww", "pop"}
16     mm.Add(m0)
17 
18     if mm.Len() != 1 {
19         t.Error("MusicManager Add() failed")
20     }
21 
22     m := mm.Find(m0.Name)
23
                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
go语言编程小游戏--贪吃蛇发布时间:2022-07-10
下一篇:
[golang]使用gomail发邮件(在Go中发送电子邮件的最佳方式)发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap