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

Yev*_*kov 3 go gpio

pi@raspberrypi:~/Desktop/go $ go run shell1.go
Run Code Online (Sandbox Code Playgroud)

结果我得到:

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
Run Code Online (Sandbox Code Playgroud)

Go文件( 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)

}
Run Code Online (Sandbox Code Playgroud)

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

 #!/bin/bash
gpio read 29
Run Code Online (Sandbox Code Playgroud)

Add*_*son 5

您在这里使用的是命令,它当然可以执行几乎任何内容。

该函数故意是通用的,因为真正的返回类型根据您执行的内容而变化。因此,当您调用输出方法时,您将获得一段字节(非常通用!)。这是它的签名:

func (c *Cmd) Output() ([]byte, error)
Run Code Online (Sandbox Code Playgroud)

如果您知道字节始终是字符串,那么您只需对字符串进行类型转换:

n, _ := strconv.ParseFloat(string(b), 10)
Run Code Online (Sandbox Code Playgroud)