相关疑难解决方法(0)

无法将数据(类型接口{})转换为类型字符串:需要类型断言

我很新,我正在玩这个通知包.

起初我的代码看起来像这样:

func doit(w http.ResponseWriter, r *http.Request) {
    notify.Post("my_event", "Hello World!")
    fmt.Fprint(w, "+OK")
}
Run Code Online (Sandbox Code Playgroud)

我想Hello World!doit上面的函数中添加换行符,但不是在上面的函数中,因为这将是非常简单的,但在handler之后如下所示:

func handler(w http.ResponseWriter, r *http.Request) {
    myEventChan := make(chan interface{})
    notify.Start("my_event", myEventChan)
    data := <-myEventChan
    fmt.Fprint(w, data + "\n")
}
Run Code Online (Sandbox Code Playgroud)

之后go run:

$ go run lp.go 
# command-line-arguments
./lp.go:15: invalid operation: data + "\n" (mismatched types interface {} and string)
Run Code Online (Sandbox Code Playgroud)

经过一段谷歌搜索后,我发现了这个问题.

然后我将我的代码更新为:

func handler(w http.ResponseWriter, r *http.Request) {
    myEventChan := make(chan interface{}) …
Run Code Online (Sandbox Code Playgroud)

go type-mismatch

160
推荐指数
4
解决办法
14万
查看次数

无法将[]字符串转换为[] interface {}

我正在编写一些代码,我需要它来捕获参数并传递它们fmt.Println
(我希望它的默认行为,写入由空格分隔的参数,然后是换行符).但它需要[]interface {}flag.Args()返回一个[]string.
这是代码示例:

package main

import (
    "fmt"
    "flag"
)

func main() {
    flag.Parse()
    fmt.Println(flag.Args()...)
}
Run Code Online (Sandbox Code Playgroud)

这将返回以下错误:

./example.go:10: cannot use args (type []string) as type []interface {} in function argument
Run Code Online (Sandbox Code Playgroud)

这是一个错误吗?不应该fmt.Println采取任何阵列?顺便说一句,我也试过这样做:

var args = []interface{}(flag.Args())
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

cannot convert flag.Args() (type []string) to type []interface {}
Run Code Online (Sandbox Code Playgroud)

是否有"Go"方式解决此问题?

type-conversion go

81
推荐指数
3
解决办法
4万
查看次数

标签 统计

go ×2

type-conversion ×1

type-mismatch ×1