无法在 strconv.ParseFloat 问题的参数中使用 (type []byte) 作为类型字符串

Cannot use (type []byte) as type string in argument to strconv.ParseFloat issue

pi@raspberrypi:~/Desktop/go $ go run shell1.go

结果我得到:

pi@raspberrypi:~/Desktop/go $ go run shell1.go
# command-line-arguments
./shell1.go:29: undefined: n
./shell1.go:29: cannot use b (type []byte) as type string in argument to strconv.ParseFloat
./shell1.go:32: undefined: n

转到文件(shell1.go)代码为:

package main

import (
    //    "net/http"
    //    "github.com/julienschmidt/httprouter"
    "fmt"
    "log"
    "os/exec"
    "strconv"
    "time"
    //"bytes"
    //"encoding/binary"
)
import _ "github.com/go-sql-driver/mysql"
import _ "database/sql"

func main() {
    for {
        time.Sleep(10 * time.Millisecond)
        cmd := exec.Command("gpio.bash")

        b, err := cmd.Output()
        if err != nil {
            log.Fatal(err)
        }
        n, _ = strconv.ParseFloat(b, 10)
        fmt.Println(string(b))
        break
    }

    fmt.Println("Button pressed!!! ", n)

}

(gpio.bash) 文件的内容只是一个读取 gpio 的命令

 #!/bin/bash
gpio read 29

您在这里使用的是 command,它当然可以执行任何操作。

该函数特意是通用的,因为真正的 return 类型因您执行的内容而异。因此,当您调用 output 方法时,您将获得一个字节片段(非常通用!)。这是它的签名:

func (c *Cmd) Output() ([]byte, error)

如果您知道字节始终是字符串,那么您只需将类型转换为字符串即可:

n, _ := strconv.ParseFloat(string(b), 10)