使用FprintF时字符串无法正确打印。

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

String not printing properly using FprintF

问题

我正在尝试编写一个IRC客户端,但是我无法使用Fprintf正确地“打印”一个字符串。以下是出现问题的方法:

func (irc *IrcConnection) sendMessage(message string, args ...interface{}) error {
    fmt.Printf("Sending: "+message, args)
    _, err := fmt.Fprintf(irc.connection, message+" \r\n", args)
    if err != nil {
        return err
    }
    return nil
}

我调用它的一个示例是:

ircConnection.sendMessage("PASS %s", ircConnection.info.password)

输出结果是"PASS

输入密码查看隐藏内容

",意味着密码打印时带有方括号,而不仅仅是密码。

起初我以为是...interface{}导致它以那种方式打印,但如果我将其更改为...string,问题仍然存在。

如果我尝试:

var test interface{} = ircConnection.info.password
fmt.Printf("%s", test)

它会打印出来而不带方括号。

我对Go语言还不太熟悉,不知道下一步该尝试什么。

英文:

I was trying my hand at an irc client but I can't get a string to "print" properly using Fprintf. This is the method that is not working:

func (irc *IrcConnection) sendMessage(message string, args ...interface{}) (error){

    fmt.Printf("Sending: "+message, args)
	_, err := fmt.Fprintf(irc.connection, message+" \r\n", args)
    if err != nil{
    	return err;
    }

    return nil
}

An example of me calling it is

ircConnection.sendMessage("PASS %s",  ircConnection.info.password)

The output ends up being "PASS

输入密码查看隐藏内容

", meaning that the password prints with square brackets instead of just the password.

I though at first it was the ...interface{} making it print like that but if I change it to ...string it has the same problem.

If I try:

var test interface{} = ircConnection.info.password
fmt.Printf("%s", test)

It prints without the brackets.

I'm pretty new to go and have no idea what to try next.

答案1

得分: 2

好的,以下是翻译好的内容:

好的,我刚刚弄清楚了。

 _, err := fmt.Fprintf(irc.connection, message+" \r\n", args)

需要改成

 _, err := fmt.Fprintf(irc.connection, message+" \r\n", args...)

我试图打印一个数组/切片。

英文:

Ok, just figured it out

 _, err := fmt.Fprintf(irc.connection, message+" \r\n", args)

needs to become

 _, err := fmt.Fprintf(irc.connection, message+" \r\n", args...)

I was trying to print an array/slice

答案2

得分: 1

你想要的是 fmt.Fprintf(irc.connection, message+" \r\n", args...) — 注意 args...,而不是 args。当你的函数声明 args ...interface{} 时,这意味着它将获取所有剩余的参数作为一个切片。当你将 args 传递给 Fprintf 时,你告诉它打印该切片。作为一个整体,一个切片。要将切片展开为参数列表,你可以使用 ...

参见 传递参数给 ... 参数

英文:

You want fmt.Fprintf(irc.connection, message+" \r\n", args...) — note the args..., not args. When your function declares args ...interface{} that means that it will get all of the remaining arguments as a slice. When you pass args to Fprintf, you're telling it to print that slice. As one thing, a slice. To flatten the slice back out into a list of arguments you use the ....

See Passing arguments to ... parameters.

huangapple
  • 本文由 发表于 2016年11月12日 13:14:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/40559810.html
匿名

发表评论

匿名网友

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

确定