当前位置: 首页 > article >正文

Go基础知识学习-习题题解

这里给出来官方教程中部分题目的答案,都是自己练习的时候写的,可以参考来提供思路。

当然了,练习还是最好自己写,要不对相关的知识点不可能理解透彻。

Exercise: Loops and Functions

package main

import (
	"fmt"
)

func Sqrt(x float64) float64 {
	z:=1.0
	for i:=0;i<10;i++{
		z -= (z*z - x) / (2*z)
		fmt.Println(z)
	}
	return z
}

func main() {
	fmt.Println(Sqrt(2))
}

Exercise: Slices

package main

import (
	"golang.org/x/tour/pic"
)

func Pic(dx, dy int) [][]uint8 {
	pic := make([][]uint8, dx)
	for x := range pic {
		pic[x] = make([]uint8, dy)
		for y := range pic[x] {
			pic[x][y] = uint8(255)
		}
	}
	return pic
}

func main() {
	pic.Show(Pic)
}

Exercise: Maps

package main

import (
	"golang.org/x/tour/wc"
	"strings"
)

func WordCount(s string) map[string]int {
	dataMap:=make(map[string]int)
	strArr:=strings.Fields(s)
	for _,x:= range strArr{
		dataMap[x]+=1
	}
	return dataMap
}

func main() {
	wc.Test(WordCount)
}

Exercise: Fibonacci closure

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	le:=-1
	ri:=1
	return func()int{
		fib:=le+ri
		le=ri
		ri=fib
		return fib
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}

Exercise: Stringers

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.

func (ip IPAddr) String() string{
	return fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
}

func int2str(a byte) string{
	return string(int(a+'0'))
}

func main() {
	hosts := map[string]IPAddr{
		"loopback":  {127, 0, 0, 1},
		"googleDNS": {8, 8, 8, 8},
	}
	for name, ip := range hosts {
		fmt.Printf("%v: %v\n", name, ip)
	}
}

Exercise: Errors

package main

import (
	"fmt"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string{
	return fmt.Sprintf("cannot Sqrt negative number: %v",float64(e))
}

func Sqrt(x float64) (float64, error) {
	if x < 0{
		return 0,ErrNegativeSqrt(x)
	}
	z := 1.0
    for i := 0; i < 10; i++ {
        z -= (z*z - x) / (2 * z)
    }
	return z, nil
}

func main() {
	fmt.Println(Sqrt(2))
	fmt.Println(Sqrt(-2))
}

Exercise: Readers

 package main

import "golang.org/x/tour/reader"

type MyReader struct{}

// TODO: Add a Read([]byte) (int, error) method to MyReader.

func (MyReader) Read(buf []byte)(int,error){
	buf[0]='A'
	return 1,nil
}


func main() {
	reader.Validate(MyReader{})
}

Exercise: rot13Reader


import (
	"io"
	"os"
	"strings"
)

type rot13Reader struct {
	r io.Reader
}

func (rot13 *rot13Reader) Read(buf []byte) (int, error) {
	count, err := rot13.r.Read(buf)
	if count > 0 && err == nil {
		for i, c := range buf {
			if c >= 'a' && c <= 'z'{
				buf[i] = 'a'+(c-'a' + 13) % 26
			}else if c >= 'A' && c <= 'Z'{
				buf[i] = 'A'+(c-'A' + 13) % 26
			}
		}
	}
	return count, err
}

func main() {
	s := strings.NewReader("Lbh penpxrq gur pbqr!")
	r := rot13Reader{s}
	io.Copy(os.Stdout, &r)
}

Exercise: Images

package main

import (
	"golang.org/x/tour/pic"
	"image/color"
	"image"
)

type Image struct{}

func (Image) Bounds() image.Rectangle{
	return image.Rect(0,0,233,233)
}

func (Image) ColorModel() color.Model{
	return color.RGBAModel;
}

func (Image) At(x,y int) color.Color{
	return color.RGBA{uint8(x),uint8(x+y),uint8(x-y),uint8(y)}
}

func main() {
	m := Image{}
	pic.ShowImage(m)
}

Exercise: Equivalent Binary Trees

package main

import (
	"fmt"

	"golang.org/x/tour/tree"
)

/*

type Tree struct {
    Left  *Tree
    Value int
    Right *Tree
}
*/

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
	if t != nil {
		Walk(t.Left, ch)
		ch <- t.Value
		Walk(t.Right, ch)
	}
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
	ch1 :=make(chan int,10)
	ch2:=make(chan int,10)
	go Walk(t1,ch1)
	go Walk(t2,ch2)
	for i:=0;i<10;i++{
		if <-ch1 != <- ch2{
			return false
		}
	}
	return true
}

func main() {
	ch:=make(chan int,10)
	go Walk(tree.New(1), ch)
	for i := 0; i < 10; i++ { // Read and print 10 values from the channel
        fmt.Println(<-ch)
    }
	fmt.Println(Same(tree.New(1), tree.New(1))) // should print true
    fmt.Println(Same(tree.New(1), tree.New(2))) // should print false
}

Exercise: Web Crawler

package main

import (
	"fmt"
	"sync"
)

type Fetcher interface {
	// Fetch returns the body of URL and
	// a slice of URLs found on that page.
	Fetch(url string) (body string, urls []string, err error)
}

type urlCache struct{
	mux sync.Mutex
	urls map[string]bool
}
func (cache *urlCache) add(url string){
	cache.mux.Lock()
	cache.urls[url] = true
	cache.mux.Unlock()
}


func (cache *urlCache) isVisited(url string) bool{
	cache.mux.Lock()
	defer cache.mux.Unlock()
	return cache.urls[url]
}

var visited = urlCache{urls: make(map[string]bool)}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher,wg *sync.WaitGroup) {
	defer wg.Done()
	// TODO: Fetch URLs in parallel.
	// TODO: Don't fetch the same URL twice.
	// This implementation doesn't do either:
	if depth <= 0||visited.isVisited(url) {
		return
	}
	visited.add(url)
	body, urls, err := fetcher.Fetch(url)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("found: %s %q\n", url, body)
	for _, u := range urls {
		wg.Add(1)
		go Crawl(u, depth-1, fetcher,wg)
	}
	return
}

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go Crawl("https://golang.org/", 4, fetcher,&wg)
	wg.Wait()
}

// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult

type fakeResult struct {
	body string
	urls []string
}

func (f fakeFetcher) Fetch(url string) (string, []string, error) {
	if res, ok := f[url]; ok {
		return res.body, res.urls, nil
	}
	return "", nil, fmt.Errorf("not found: %s", url)
}

// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
	"https://golang.org/": &fakeResult{
		"The Go Programming Language",
		[]string{
			"https://golang.org/pkg/",
			"https://golang.org/cmd/",
		},
	},
	"https://golang.org/pkg/": &fakeResult{
		"Packages",
		[]string{
			"https://golang.org/",
			"https://golang.org/cmd/",
			"https://golang.org/pkg/fmt/",
			"https://golang.org/pkg/os/",
		},
	},
	"https://golang.org/pkg/fmt/": &fakeResult{
		"Package fmt",
		[]string{
			"https://golang.org/",
			"https://golang.org/pkg/",
		},
	},
	"https://golang.org/pkg/os/": &fakeResult{
		"Package os",
		[]string{
			"https://golang.org/",
			"https://golang.org/pkg/",
		},
	},
}

 


http://www.kler.cn/a/233891.html

相关文章:

  • 11Java面向对象高级(篇2,Java程序的核心套路!!!!)
  • 使用ookii-dialogs-wpf在WPF选择文件夹时能输入路径
  • Java-Redisson分布式锁+自定义注解+AOP的方式来实现后台防止重复请求扩展
  • 【Linux篇】面试——用户和组、文件类型、权限、进程
  • 设备接入到NVR管理平台EasyNVR多品牌NVR管理工具/设备的音视频配置参考
  • Java项目实战II基于Spring Boot的药店管理系统的设计与实现(开发文档+数据库+源码)
  • 2024年度十余爆款爱心表白代码,还不进来瞅瞅?(一)
  • Git的基础操作指令
  • java大数据hadoop2.9.2 Flume安装操作
  • Jupyter Notebook如何在E盘打开
  • 机器学习系列——(十八)K-means聚类
  • Vue-56、Vue技术路由的使用
  • 【大数据面试题】005 谈一谈 Flink Watermark 水印
  • 突破编程_C++_面试(基础知识(9))
  • 飞书上传图片
  • FPS游戏框架漫谈第二十天
  • 【大厂AI课学习笔记】【1.5 AI技术领域】(10)对话系统
  • C++ 位运算
  • Github 2024-02-06 开源项目日报Top9
  • 波奇学Linux:文件重定向和虚拟文件系统
  • 2024年 前端JavaScript入门到精通 第一天
  • 2-8 单链表+双链表+模拟栈+模拟队列
  • [Angular 基础] - 指令(directives)
  • Go语言每日一题——链表篇(七)
  • ANSI Escape Sequence 下落的方块
  • Stable Diffusion 模型下载:ToonYou(平涂卡通)