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+"
", 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 [password]", 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.
Ok, just figured it out
_, err := fmt.Fprintf(irc.connection, message+"
", args)
needs to become
_, err := fmt.Fprintf(irc.connection, message+"
", args...)
I was trying to print an array/slice
You want fmt.Fprintf(irc.connection, message+" ", 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 ...
.