Go - print without spaces between elements

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

I want to print two lines without a space, namely β€œab”, but β€œa” will be printed above.

Go fmt

Am I just switching to using Printf ?

 fmt.Printf("%s%s\n","a","b") 
+5
source share
5 answers

Plain old printing will work if you make the last element "\ n".
It will also be easier to read if you are not using printf style formatting.

See here in the game

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

will print:

 ab ab ab 
+10
source

How can this be found in the doc :

Println format using default formats for its operands and records to standard output. Spaces are always added between operands and a new line is added. It returns the number of bytes written and any write error.

So, you need to either do what you already said or concatenate the lines before printing:

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

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

+2
source

Println relies on doPrint(args, true, true) , where the first argument is addspace and the second is addnewline . This way, Prinln with multiple arguments will always print a space.

There seems to be no call to doPrint(args, false, true) that you want. Printf might be a Print solution, but you have to add a new line.

+1
source

You will need to compare performance, but I would rather use the following than Printf :

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

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

0
source

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) } 
0
source

Source: https://habr.com/ru/post/1202945/


All Articles