16
fmt.Println("a","b")

I want to print the two strings without space padding, namely "ab", but the above will print "a b".

Go fmt

Do I just switch to using Printf ?

fmt.Printf("%s%s\n","a","b")
icecrime
  • 74,451
  • 13
  • 99
  • 111
null
  • 889
  • 1
  • 13
  • 24

5 Answers5

18

Plain old print will work if you make the last element "\n".
It will also be easier to read if you aren't used to printf style formatting.

See here on play

fmt.Println("a","b")
fmt.Print("a","b","\n")
fmt.Printf("%s%s\n","a","b")

will print:

a b
ab
ab
David Budworth
  • 11,248
  • 1
  • 36
  • 45
  • 5
    Don't forget `fmt.Println("a" + "b")` – AndrewN Sep 21 '14 at 21:18
  • fmt.Print("a","b","\n") may hard code the \n which may by operating system specific. E.g. DOS vs Linux. fmt.Println("a" + "b") might could get around that. – null Nov 20 '19 at 23:28
12

As it can be found in the doc:

Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

So you either need to do what you already said or you can concatenate the strings before printing:

fmt.Println("a"+"b")

Depending on your usecase you can use strings.Join(myStrings, "") for that purpose.

Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
  • 4
    I wonder what the rationale was for making `Print` behave subtly differently to `Println` like this. – Maxpm Sep 15 '17 at 08:43
2

Println relies on doPrint(args, true, true), where first argument is addspace and second is addnewline. So Prinln ith multiple arguments will always print space.

It seems there is no call of doPrint(args, false, true) which is what you want. Printf may be a solution, Print also but you should add a newline.

GHugo
  • 2,584
  • 13
  • 14
-1

You'd have to benchmark to compare performance, but I'd rather use the following than a Printf:

fmt.Println(strings.Join([]string{"a", "b"}, ""))

Remember to import "strings", and see strings.Join documentation for an explanation.

icecrime
  • 74,451
  • 13
  • 99
  • 111
  • fmt.Print("a","b","\n") looks much more readable. One issue may be hard coding the \n which may by operating system specific. E.g. DOS vs Linux. – null Nov 20 '19 at 23:26
-1

the solution in my project

package main

import "fmt"

var formatMap = map[int]string{
    0: "",
    1: "%v",
}

func Println(v ...interface{}) {
    l := len(v)
    if s, isOk := formatMap[l]; !isOk {
        for i := 0; i < len(v); i++ {
            s += "%v"
        }
        formatMap[l] = s
    }
    s := formatMap[l] + "\n"
    fmt.Printf(s, v...)
}
func main() {
    Println()
    Println("a", "b")
    Println("a", "b")
    Println("a", "b", "c", 1)
}
JessonChan
  • 216
  • 2
  • 3