how to split long lines for fmt.sprintf - go

I have a very long line in fmt.Sprintf. How do I split it in the code? I don't want to put everything in a single line so the code looks ugly.
fmt.Sprintf("a:%s, b:%s ...... this goes really long")

Use string concatenation to construct a single string value on multiple lines:
fmt.Sprintf("a:%s, b:%s " +
" ...... this goes really long",
s1, s2)
The long string in this example is built at compile time because the string concatenation is a constant expression.
You can split the string at contained newlines using a raw string literal:
fmt.Sprintf(`this text is on the first line
and this text is on the second line,
and third`)

You can also use raw string literals inside backticks, like this:
columns := "id, name"
table := "users"
query := fmt.Sprintf(`
SELECT %s
FROM %s
`, columns, table)
fmt.Println(query)
There are a few caveats to this approach:
Raw strings don't parse escape sequences
All the whitespace will be preserved, so there will be a newline and then several tabs before the FROM clause in this query.
These problems can be a challenge for some, and the whitespace will produce some ugly resulting strings. However, I prefer this approach as it allows you to copy and paste long, complex SQL queries outside of your code and into other contexts, like sql worksheets for testing.

Since you're using Sprintf already (meaning you'll have a string like "this is the string with %s placeholders in it") you could just add more place holders to the string and then put the values you'd like there on their own lines like;
fmt.Sprintf("This %s is so long that I need %s%s%s for the other three strings,
"string",
"some super long statement that I don't want to type on 50 lines",
"another one of those",
"yet another one of those")
Another option is just to use string concatenation like "string 1" + "string 2".

Another option is strings.Builder:
package main
import (
"fmt"
"strings"
)
func main() {
b := new(strings.Builder)
fmt.Fprint(b, "North")
fmt.Fprint(b, "South")
println(b.String() == "NorthSouth")
}
https://golang.org/pkg/strings#Builder

Why don't you split it out:
fmt.Sprintf("a:%s, b:%s ", x1, x2)
fmt.Sprintf("...... ")
fmt.Sprintf("this goes really long")
Or you can split them out with the plus sign as indicated by MuffinTop.

Related

Golang Typecasting

I have specific questions for my project
input = "3d6"
I want to convert this string some parts to integer. For instance I want to use input[0] like integer.
How can I do this?
There's two problems here:
How to convert a string to an integer
The most straightforward method is the Atoi (ASCII to integer) function in the strconv package., which will take a string of numeric characters and coerce them into an integer for you.
How to extract meaningful components of a known string pattern
In order to use strconv.Atoi, we need the numeric characters of the input by themselves. There's lots of ways to slice and dice a string.
You can just grab the first and last characters directly - input[:1] and input[2:] are the ticket.
You could split the string into two strings on the character "d". Look at the split method, a member of the strings package.
For more complex problems in this space, regular expressions are used. They're a way to define a pattern the computer can look for. For example, the regular expression ^x(\d+)$ will match on any string that starts with the character x and is followed by one or more numeric characters. It will provide direct access to the numeric characters it found by themselves.
Go has first class support for regular expressions via its regexp package.
For example,
package main
import (
"fmt"
)
func main() {
input := "3d6"
i := int(input[0] - '0')
fmt.Println(i)
}
Playground: https://play.golang.org/p/061miKcXdIF
Output:
3

Why is there a comma in this Golang struct creation?

I have a struct:
type nameSorter struct {
names []Name
by func(s1, s2 *Name) bool
Which is used in this method. What is going on with that comma? If I remove it there is a syntax error.
func (by By) Sort(names []Name) {
sorter := &nameSorter{
names: names,
by: by, //why does there have to be a comma here?
}
sort.Sort(sorter)
Also, the code below works perfectly fine and seems to be more clear.
func (by By) Sort(names []Name) {
sorter := &nameSorter{names, by}
sort.Sort(sorter)
For more context this code is part of a series of declarations for sorting of a custom type that looks like this:
By(lastNameSort).Sort(Names)
This is how go works, and go is strict with things like comma and parentheses.
The good thing about this notion is that when adding or deleting a line, it does not affect other line. Suppose the last comma can be omitted, if you want to add a field after it, you have to add the comma back.
See this post: https://dave.cheney.net/2014/10/04/that-trailing-comma.
From https://golang.org/doc/effective_go.html#semicolons:
the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them
In other words, the programmer is unburdened from using semicolons, but Go still uses them under the hood, prior to compilation.
Semicolons are inserted after the:
last token before a newline is an identifier (which includes words like int and float64), a basic literal such as a number or string constant, or one of the tokens break continue fallthrough return ++ -- ) }
Thus, without a comma, the lexer would insert a semicolon and cause a syntax error:
&nameSorter{
names: names,
by: by; // semicolon inserted after identifier, syntax error due to unclosed braces
}

How to print os.args[1:] without braces in Go?

When I tried to print command line arguments using
fmt.Println(os.Args[1:])
I got result like
[Gates Bill]
How can I get rid of the [] around the arguments? And Go seems to eat all the commas in the arguments, how can I get the output like
Last name, First name
Gates, Bill
You should use strings.Join for this. Try,
fmt.Printf("%s, Author of The Art of Computer Programming", strings.Join(os.Args[1:], ", "))
Join returns a string with ", " inserted between each argument.
The reason it's outputting the brackets is because you're passing a slice into the print command.
What you want to do is take each command and put them into a string to be printed as needed.
firstname := os.Args[1]
lastname := os.Args[2]
fmt.Println(lastname + ", " + firstname)
You should also take a look at the strings package as was pointed out by Chandru. There's a bunch of goodies in there to help with dealing with strings.
See: https://golang.org/pkg/strings/

How do you print a dollar sign $ in Dart

I need to actually print a Dollar sign in Dart, ahead of a variable. For example:
void main()
{
int dollars=42;
print("I have $dollars."); // I have 42.
}
I want the output to be: I have $42. How can I do this? Thanks.
Dart strings can be either raw or ... not raw (normal? cooked? interpreted? There isn't a formal name). I'll go with "interpreted" here, because it describes the problem you have.
In a raw string, "$" and "\" mean nothing special, they are just characters like any other.
In an interpreted string, "$" starts an interpolation and "\" starts an escape.
Since you want the interpolation for "$dollars", you can't use "$" literally, so you need to escape it:
int dollars = 42;
print("I have \$$dollars.");
If you don't want to use an escape, you can combine the string from raw and interpreted parts:
int dollars = 42;
print(r"I have $" "$dollars.");
Two adjacent string literals are combined into one string, even if they are different types of string.
You can use a backslash to escape:
int dollars=42;
print("I have \$$dollars."); // I have $42.
When you are using literals instead of variables you can also use raw strings:
print(r"I have $42."); // I have $42.

Splitting A String In Two Parts(REALBASIC)

I am trying to split a string at the character ":" but cant create two separate strings from the split. If somebody could help me, I would appreciate it.
In RealBasic, the Split method doesn't create two (or more) separate strings but rather a single string array.
Dim s() As String = Split("Zero:One:Two", ":")
's() now contains the substrings like so:
's(0) = "Zero"
's(1) = "One"
's(2) = "Two"
Actually, the code is incorrect. It should be:
Dim s() As String = Split("Zero:One:Two", ":")
If you don't pass in the delimiter it assumes a space which wouldn't work in this case.
The online docs are at http://docs.realsoftware.com/index.php/Split
Split is best for actually splitting the text, but you can also use the string-manipulation methods: Left, Right, Mid and InStr.

Resources