无法将类型 []byte 作为 strconv.ParseFloat 函数的参数中的字符串类型使用。

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

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

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)

}

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

#!/bin/bash
gpio read 29

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

As result i am getting:

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

Go file (shell1.go) code is:

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)

}

Content of (gpio.bash) file is just one command to read gpio

 #!/bin/bash
gpio read 29

答案1

得分: 5

你在这里使用了一个command,它可以执行几乎任何命令。

这个函数是故意设计成通用的,因为真正的返回类型取决于你执行的内容。因此,当你调用output方法时,会得到一个字节切片(非常通用!)。这是它的签名:

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

如果你知道这些字节始终是一个字符串,那么你只需要将其转换为字符串类型:

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

You are working with a command here, which can of course execute just about anything.

The function is purposely generic, as the true return type varies depending on what you executed. Thus, when you call the output method, you are given a slice of bytes (very generic!). Here is its signature:

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

If you know that the bytes will always be a string, then you simply have to do a type conversion to a string:

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

huangapple
  • 本文由 发表于 2017年3月8日 05:53:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/42659045.html
匿名

发表评论

匿名网友

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

确定