'Rune text not terminated' error when trying to run gofmt -r using exec.Command

WBOY
Release: 2024-02-11 18:10:07
forward
736 people have browsed it

尝试使用 exec.Command 运行 gofmt -r 时出现“符文文字未终止”错误

php Editor Youzi encountered a "rune text not terminated" error when using exec.Command to run gofmt -r. This error may be caused by a symbol in the command not terminating correctly. To solve this problem, we can check that the symbols in the command are paired correctly and make sure that each symbol has the correct terminator. Also, try using escape characters to handle commands that contain special symbols. I hope these methods can help developers who encounter the same problem!

Question content

In the following directory structure,

.
├── foo.go
├── go.mod
└── main.go
Copy after login

I have a foo.go which has a simple type definition:

package main

type foo struct {
    baz string
}
Copy after login

If I run ngofmt -r from the command line to replace the variable names, it works:

> gofmt -r 'foo -> bar' foo.go
package main

type bar struct {
    baz string
}
Copy after login

But if I try to use the program to do this from main.go

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    combinedoutput, err := exec.command("gofmt", "-r", "'foo -> bar'", "foo.go").combinedoutput()
    if err != nil {
        log.fatalf("gofmt foo.go: %v. combined output: %s", err, combinedoutput)
    }
    fmt.println(string(combinedoutput))
}
Copy after login

I get the error:

> go run main.go
2023/01/14 23:42:07 gofmt foo.go: exit status 2. Combined output: parsing pattern 'Foo  at 1:1: rune literal not terminated
exit status 1
Copy after login

Do you know what caused it?

Workaround

You do not need to quote arguments to exec.command; quoting is a feature of the shell and does not apply when making system calls. It's also not necessary, since in the shell quoting is to describe the parameters, but in exec.command the parameters are separated into parameters for the function call.

specific:

exec.command("gofmt", "-r", "'foo -> bar'", "foo.go")
Copy after login

should be

exec.Command("gofmt", "-r", "Foo -> Bar", "foo.go")
Copy after login

The above is the detailed content of 'Rune text not terminated' error when trying to run gofmt -r using exec.Command. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template