我最近在我的一个golang项目中使用了一个map,它有像这样的键的函数指针:
map[*functiontype] somestructtype
Run Code Online (Sandbox Code Playgroud)
我的一位同事说这是一个坏主意,所以现在我不确定这是否可行.我最初认为没问题,因为方法指针可以检查是否相等并且是不可变的.有人可以就此事提供一些推理吗?
完整的例子:
package main
import "fmt"
type s struct {
string
}
type f func() string
func func1() string { return "func 1" }
func func2() string { return "func 2" }
func main() {
// make two functions and two pointers to them
f1, f2 := func1, func2
p1, p2 := (*f)(&f1), (*f)(&f2)
// make a map of their function pointers
m := make(map[*f]s)
m[p1] = s{"struct 1"}
m[p2] = s{"struct 2"}
// print out the …Run Code Online (Sandbox Code Playgroud) 我已经实现了一个自定义错误类型,并且在 nil 值方面确实得到了奇怪的行为。当我将自定义错误作为标准错误接口传递时,这永远不会被识别为 nil,即使自定义错误返回为 nil。
看看这个小测试程序:
package main
import (
"fmt"
"strconv"
)
type CustomError struct {
Code int
}
func (e *CustomError) Error() string {
return strconv.Itoa(e.Code)
}
func FailCustom(dofail bool) *CustomError {
if dofail {
return &CustomError{Code: 42}
} else {
return nil
}
}
func WrapFailCustom(dofail bool) error {
return FailCustom(dofail)
}
func main() {
err := WrapFailCustom(false)
if err == nil {
fmt.Println("err is nil")
} else {
fmt.Println("err is not nil")
}
}
Run Code Online (Sandbox Code Playgroud)
在操场上也一样:https …
我正在浏览 Go Bootcamp 并且正在阅读 Go Concurrency 一章。我之前在编程中从未使用过并发,不理解这个程序的输出:
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 2; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
Run Code Online (Sandbox Code Playgroud)
输出:
hello
world
hello
Program exited.
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么“世界”不像“你好”那样打印两次吗?也许阐明使用并发的想法?
请注意,此处为Go Playground 链接。