如何修改旧版本中的printer.Fprint,以便在最新版本的Go上运行

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

How to modify printer.Fprint in old version to can run on latest version of Go

问题

str := new(bytes.Buffer) //old code
printer.Fprint(str, c) //old code
str := new(token.FileSet) //new code
printer.Fprint(os.Stdout, str, c) //new code

source += "\t" + str.String() + ";\n"

In this code i try to change str's value from new(bytes.Buffer) to new(token.FileSet) because Fprint's argument requier;
func Fprint(output io.Writer, fset *token.FileSet, node interface{}) os.Error //latest ver.
now, i'm stucking in error str.String() because str don't have method String().
I can't update my code for run in latest version of Go because a changed of printer.Fprint()
How to volve this?

英文:
str := new(bytes.Buffer) //old code
printer.Fprint(str, c)   //old code	
str := new(token.FileSet) //new code
printer.Fprint(os.Stdout, str, c) //new code	

source += "\t" + str.String() + ";\n"	

In this code i try to change str's value from new(bytes.Buffer) to new(token.FileSet) because Fprint's argument requier; <br />
func Fprint(output io.Writer, fset *token.FileSet, node interface{}) os.Error //latest ver.<br />
now, i'm stucking in error str.String() because str don't have method String().
I cann't update my code for run in latest version of Go because a changed of printer.Fprint()<br />
How to volve this?

答案1

得分: 1

这是一个示例程序。

package main

import (
	"bytes"
	"fmt"
	"go/parser"
	"go/printer"
	"go/token"
)

func main() {
	const src = `package main
	func main() {}
	`

	fset := token.NewFileSet()
	ast, err := parser.ParseFile(fset, "", src, parser.ParseComments)
	if err != nil {
		panic(err)
	}

	var buf bytes.Buffer
	printer.Fprint(&buf, fset, ast)

	fmt.Print(buf.String())
}

输出:

package main

func main()	{}
英文:

Here's a sample program.

package main

import (
	&quot;bytes&quot;
	&quot;fmt&quot;
	&quot;go/parser&quot;
	&quot;go/printer&quot;
	&quot;go/token&quot;
)

func main() {
	const src = `package main
	func main() {}
	`

	fset := token.NewFileSet()
	ast, err := parser.ParseFile(fset, &quot;&quot;, src, parser.ParseComments)
	if err != nil {
		panic(err)
	}

	var buf bytes.Buffer
	printer.Fprint(&amp;buf, fset, ast)

	fmt.Print(buf.String())
}

Output:

package main

func main()	{}

huangapple
  • 本文由 发表于 2011年8月14日 04:41:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/7053141.html
匿名

发表评论

匿名网友

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

确定