What does the back tick do in golang - go

I have a variable defined like this
var selectStatement = `
SELECT role FROM abc INNER JOIN xyz ON (abc.name = 'Service list')
`
Now what I want to do is instead of using hardcoded 'Service list' I want to read a variable value something like
var myvar = "operation"
var selectStatement = `
SELECT role FROM abc INNER JOIN xyz ON (abc.name = $myvar)
`
I know its very simple if there was "string" instead of `string`.
How can I achieve this. What is the difference between "string" and `string`?

` That back tick, (on the tilde key) is for declaring string literals. It makes it so you can have quotes and new lines and they are interpreted literally rather than breaking the string.
To solve your bigger problem use fmt.Sprintf so...
var selectStatement = `
SELECT role FROM abc INNER JOIN xyz ON (abc.name = '%s')
`
selectStatement = fmt.Sprintf(selectStatement, ValueGoingWherePercentSIsNow)

This question is actually two questions: one in a topic and one in a body of the question.
What does ` do in GoLang
`string` is a raw string literal. In a raw string literal (within the quotes) any character may appear except backquote. A raw string literal is uninterpreted (implicitly UTF-8-encoded) characters. It means that backslashes have no special meaning and the string may contain newlines.
"string" is an interpreted string literal. With interpreted string literal backslash escapes interpreted as they are in rune literals. It can't contain newlines, although the escape sequence \n is interpreted as a newline.
String interpolation
It is possible to do with fmt.Sprintf
func main(){
myvar := "operation"
selectStatement := `
SELECT role FROM abc INNER JOIN xyz ON (abc.name = %s)
`
interpolated := fmt.Sprintf(selectStatement, myvar)
}
Playground

Related

ruby on rails replace single-quotes with double-quote in a string

I am trying to replace a single-quote with double quotes inside a string, as following:
current_res = 25
lowest_res = 15
str = "The result of the child is '#{current_res}' and the lowest grade is '#{lowest_res }'."
I need the output to look like:
str = The result of the child is "25" and the lowest grade is "15".
I tried different method using gsub but nothing work so far. Any ideas?
If that's the only case you're covering where you need to show some output in double quoted string then. How about something simple like following
str = "The result of the child is \"#{current_res}\" and the lowest grade is \"#{lowest_res }\" ."
You can escape quotes in double quoted strings.

how to split long lines for fmt.sprintf

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.

String literal without need to escape backslash

In C#, I can write backslashes and other special characters without escaping by using # before a string, but I have to escape double-quotes.
C#
string foo = "The integer division operator in VisualBASIC is written \"a \\ b\"";
string bar = #"The integer division operator in VisualBASIC is written \"a \ b\""
In Ruby, I could use the single-quote string literal, but I'd like to use this in conjuction with string interpolation like "text #{value}". Is there an equivalent in Ruby to # in C#?
There is somewhat similar thing available in Ruby. E.g.
foo = %Q(The integer division operator in VisualBASIC is written "a \\ b" and #{'interpolation' + ' works'})
You can also interpolate strings in it. The only caveat is, you would still need to escape \ character.
HTH
You can use heredoc with single quotes.
foo = <<'_'
The integer division operator in VisualBASIC is written "a \ b";
_
If you want to get rid of the newline character at the end, then chomp it.
Note that this does not work with string interpolation. If you want to insert evaluated expressions within the string, you can use % operation after you create the string.
foo = <<'_'
text %{value}
_
foo.chomp % {value: "foo"}

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.

Remove email address from string in Ruby

I have the following code which is supposed to be removing a particular email address from a string if it exists. The problem is i get the error "invalid range "y-d" in string transliteration (ArgumentError)" which I assume is because it's treating my input as a regex. I will need to do this delete by a variable in the actual code, not a string literal but this is a simplified version of the problem.
So how do I properly perform this operation?
myvar = "test1#my-domain.com test2#my-domain.com"
myvar = myvar.delete("test1#my-domain.com")
Try
myvar = "test1#my-domain.com test2#my-domain.com"
myvar = myvar.gsub("test1#my-domain.com", '').strip
String#delete(str) does not delete the literal string str but builds a set out of individual characters of str and deletes all occurrences of these characters. try this:
"sets".delete("test")
=> ""
"sets".delete("est")
=> ""
The hyphen has a special meaning, it defines a range of characters. String#delete("a-d") will delete all occurrences of a,b,c and d characters. Range boundary characters should be given in ascending order: you should write "a-d" but not "d-a".
In your original example, ruby tries to build a character range from y-d substring and fails.
Use String#gsub method instead.
You can do it like this
myvar = "test1#my-domain.com test2#my-domain.com"
remove = "test1#my-domain.com"
myvar.gsub!(remove, "")

Resources