In Python, I can declare a variable as d ='/some/dir/%s' and later replace %s with any value as
>>> d = '/some/dir/%s'
>>> d % "hello"
'/some/dir/hello'
Is it possible to do the same in Go? If so, how?
Yes, fmt.Sprintf does that:
d := "/some/dir/%s"
fmt.Sprintf(d, "hello") // Returns "/some/dir/hello"
Related
I am new to Go and understanding simple syntax and functions. Here I am confused between Print and Printf function. The output of those function is similar, so what is the difference between these two functions?
package main
import (
"fmt"
"bufio"
"os"
)
func main(){
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Text: ")
str, _ := reader.ReadString('\n')
fmt.Printf(str)
fmt.Print(str)
}
I read https://golang.org/pkg/fmt/#Print to understand, but I did not understand it.
From the docs about Printing:
For each Printf-like function, there is also a Print function that takes no format and is equivalent to saying %v for every operand. Another variant Println inserts blanks between operands and appends a newline.
So Printf takes a format string, letting you tell the compiler what format to output your variables with and put them into a string with other information, whereas Print just outputs the variables as they are. Generally you'd prefer to use fmt.Printf, unless you're just debugging and want a quick output of some variables.
In your example you're sending the string you want to print as the format string by mistake, which will work, but is not the intended use. If you just want to print one variable in its default format it's fine to use Print.
Printf method accepts a formatted string for that the codes like "%s" and "%d" in this string to indicate insertion points for values. Those values are then passed as arguments.
Example:
package main
import (
"fmt"
)
var(
a = 654
b = false
c = 2.651
d = 4 + 1i
e = "Australia"
f = 15.2 * 4525.321
)
func main(){
fmt.Printf("d for Integer: %d\n", a)
fmt.Printf("6d for Integer: %6d\n", a)
fmt.Printf("t for Boolean: %t\n", b)
fmt.Printf("g for Float: %g\n", c)
fmt.Printf("e for Scientific Notation: %e\n", d)
fmt.Printf("E for Scientific Notation: %E\n", d)
fmt.Printf("s for String: %s\n", e)
fmt.Printf("G for Complex: %G\n", f)
fmt.Printf("15s String: %15s\n", e)
fmt.Printf("-10s String: %-10s\n",e)
t:= fmt.Sprintf("Print from right: %[3]d %[2]d %[1]d\n", 11, 22, 33)
fmt.Println(t)
}
As per docs
Print: will print number variables, and will not include a line break at the end.
Printf: will not print number variables, and will not include a line break at the end.
Printf is for printing formatted strings. And it can lead to more readable printing.
For more detail visit this tutorial.
I have a string in Golang called mystring and I want to put it between 2 percentage signs (like this %mystring%). However until now I wasn't able to do it.
The things that I have tried are:
value := fmt.Sprintf("%%s%",mystring)
value := fmt.Sprintf("%s%s%s","%",mystring,"%")
value := fmt.Sprintf("/% %s/%",mystring)
But when I print it, in the end I receive a nil. Example: the value of mystring is "HelloWorld" then I get: %HelloWorld%nil
Right now I am receiving this as result:
/%s/%!(NOVERB)%!(EXTRA string=HelloWorld)<nil>
So, what am I missing?
Thanks.
You need to escape the %'s in format string using another %:
value := fmt.Sprintf("%%%s%%",mystring)
Use %% in your format string for an actual %.
For example:
func main() {
mystring := "hello"
value := fmt.Sprintf("%%%s%%", mystring)
fmt.Println(value)
}
Prints: %hello%
This is clearly documented at the beginning of the docs for fmt:
%% a literal percent sign; consumes no value
I saw in some Specman e code example the use of := (colon-equal sign), e.g.:
var regs_type := rf_manager.get_exact_subtype_of_instance(graphics_regs);
When and why should we use := ?
Thank you for your help.
The := means declare a variable of the type the expression on the right returns and assign it to that value. Basically, in your example, the function get_exact_subtype_of_instance(...) returns a value of type rf_struct. The regs_type variable will be declared to that type.
This code is equivalent to (but shorter than):
var regs_type : rf_struct = rf_manager.get_exact_subtype_of_instance(graphics_regs);
This syntax is particularly helpful when casting:
var foo := some_struct.as_a(FOO some_struct_type);
We can use the following syntax for go variable declaration
var num int
var str string
but is there any shorthand in go for doing the same thing?
for example we can do so in python simply saying:
num = 13
strings = "Hello World"
or even
num, strings = 13,"Hello World"
The variable declaration can initialize multiple variables:
var x, y float32 = -1, -2
Or (short variable declaration with :=)
i, j := 0, 10
So this would work: play.golang.org
package main
import "fmt"
func main() {
a, b := 1, "e"
fmt.Printf("Hello, playground %v %v", b, a)
}
Output:
Hello, playground e 1
The := syntax is shorthand for declaring and initializing a Go variable .
For example:
to declare e string var we can simple use
str := "Hello world"
Short variable declarations
The := operator is the short variable declaration operator. This operator is used to both declare and initialize a variable.
Example:
package main
import "fmt"
func main() {
firstName := "Joey"
fmt.Println(firstName)
}
The variable type is not vital because the Go compiler is able to derive the type based on the value you have assigned. Since we are assigning a string to firstName, firstName is allocated as a variable type as string.
I'm following this tutorial, specifically exercise 8:
http://tour.golang.org/#8
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
Specifically what does the := mean? Searching for Go documentation is very hard, ironically.
A short variable declaration uses the syntax:
ShortVarDecl = IdentifierList ":=" ExpressionList .
It is a shorthand for a regular variable declaration with initializer expressions but no types:
Keep on going to page 12 of the tour!
A Tour of Go
Short variable declarations
Inside a function, the := short assignment statement can be used in
place of a var declaration with implicit type.
(Outside a function, every construct begins with a keyword and the :=
construct is not available.)
As others have explained already, := is for both declaration, and assignment, whereas = is for assignment only.
For example, var abc int = 20 is the same as abc := 20.
It's useful when you don't want to fill up your code with type or struct declarations.
The := syntax is shorthand for declaring and initializing a variable, example f := "car" is the short form of var f string = "car"
The short variable declaration operator(:=) can only be used for declaring local variables. If you try to declare a global variable using the short declaration operator, you will get an error.
Refer official documentation for more details
:= is not an operator. It is a part of the syntax of the Short variable declarations clause.
more on this: https://golang.org/ref/spec#Short_variable_declarations
According to my book on Go, it is just a short variable declaration statement
exactly the same as
var s = ""
But it is more easy to declare, and the scope of it is less expansive. A := var decleration also can't have a type of interface{}. This is something that you will probably run into years later though
:= represents a variable, we can assign a value to a variable using :=.