Go语言切片练习中出现错误。

huangapple go评论95阅读模式
英文:

Error in Go's slices exercise

问题

我正在尝试解决切片练习。我目前的解决方案是:

package main

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

func Pic(dx, dy int) [][]uint8 {
    picture := make([][]uint8, dy)
    
    x := dx
    
    for iy := 0; iy < dy; iy++ {
        picture[iy] = make([]uint8, dx)
        
        for ix := 0; ix < dx; ix++ {
            x = (x+dy)/2
            picture[iy][ix] = uint8(x)
        }
    }
    
    return picture
}

func main() {
    pic.Show(Pic(1,2))
}

但是我得到了以下错误:

tmp/sandbox931798243/main.go:23: cannot use Pic(1, 2) (type [][]uint8)
as type func(int, int) [][]uint8 in argument to pic.Show

我做错了什么?这可能是沙盒的一个错误吗?

英文:

I'm trying to solve the slices exercise. My current solution is

package main

import &quot;golang.org/x/tour/pic&quot;

func Pic(dx, dy int) [][]uint8 {
    picture := make([][]uint8, dy)
	
	x := dx
	
	for iy := 0; iy &lt; dy; iy++ {
		picture[iy] = make([]uint8, dx)
		
		for ix := 0; ix &lt; dx; ix++ {
			x = (x+dy)/2
			picture[iy][ix] = uint8(x)
		}
	}
	
	return picture
}

func main() {
	pic.Show(Pic(1,2))
}

But I'm getting the following error

> tmp/sandbox931798243/main.go:23: cannot use Pic(1, 2) (type [][]uint8)
> as type func(int, int) [][]uint8 in argument to pic.Show

What am I doing wrong? Might that be a bug with the sandbox?

答案1

得分: 6

pic.Show 接受一个类型为 func(int, int) [][]uint8 的单个参数 - 你需要传递一个函数给它。你现在传递的是执行 func(int, int) [][]uint8 的结果,也就是一个 [][]uint8。你想要的是:

pic.Show(Pic)

传递你的函数 Pic 本身,它符合要求。

英文:

pic.Show takes a single argument of type func(int, int) [][]uint8 - you need to pass it a function. You're passing the result of executing a func(int, int) [][]uint8, i.e. a [][]uint8. What you want would be:

pic.Show(Pic)

Passing in your function Pic itself, which meets the requirements.

huangapple
  • 本文由 发表于 2017年6月6日 01:53:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/44374829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定