package <packagename>
import <packagename>
src
" directory contains GO source files organized into packages.pkg
" directory contains package objects.bin
" directory contains executable commandsfunc swap(sw []int) {
for a, b := 0, len(sw)-1; a < b; a, b = a+1, b-1 {
sw[a], sw[b] = sw[b], sw[a]
}
}
func main() {
x := []int{3, 2, 1}
swap(x)
fmt.Println(x)
// Output: [1 2 3]
}
*
operator : This operator is called a dereferencing operator and is used for accessing the value in the address stored by the pointer. &
operator : This operator is called the address operator and is used for returning the address of the variable stored in the pointer. &x
for storing the address of variable x. The pointer variable is stored in address 0x0208. Now to get the value stored in the address that is stored in the pointer, we can just write int z:= *Y
package main
import "fmt"
func do(i interface{}) {
switch v := i.(type) {
case int:
fmt.Printf("Double %v is %v\n", v, v*2)
case string:
fmt.Printf("%q is %v bytes long\n", v, len(v))
default:
fmt.Printf("I don't know type %T!\n", v)
}
}
func main() {
do(21)
do("hello")
do(true)
}
Double 21 is 42
"hello" is 5 bytes long
I don't know type bool!
go
keyword before the function declaration.go f(x, y, z)
for loop
.package main
func main() {
quit := make(chan bool)
go func() {
for {
select {
case <-quit:
return
default:
// …
}
}
}()
// …
quit <- true
}
package main
import (
"fmt"
)
func reverseValues(a,b string)(string, string){
return b,a //notice how multiple values are returned
}
func main(){
val1,val2:= reverseValues("freetime","learning") // notice how multiple values are assigned
fmt.Println(val1, val2)
}
learning freetime
package main
import "fmt"
func main() {
// Creating an array
arr := [6]string{"This","is", "a","Go","interview","question"}
// Print array
fmt.Println("Original Array:", arr)
// Create a slice
slicedArr := arr[1:4]
// Display slice
fmt.Println("Sliced Array:", slicedArr)
// Length of slice calculated using len()
fmt.Println("Length of the slice: %d", len(slicedArr))
// Capacity of slice calculated using cap()
fmt.Println("Capacity of the slice: %d", cap(slicedArr))
}
Original Array: [This is a Go interview question]
Sliced Array: [is a Go]
Length of the slice: %d 3
Capacity of the slice: %d 5
func(name type) method_name(param_list)(return_type)
{
//code
}
package main
import "fmt"
func main() {
// Creating and initializing strings
// using var keyword
var str1 string
str1 = "Hello "
var str2 string
str2 = "Reader!"
// Concatenating strings
// Using + operator
fmt.Println("New string 1: ", str1+str2)
// Creating and initializing strings
// Using shorthand declaration
str3 := "Welcome"
str4 := "FreetimeLearning.com"
// Concatenating strings
// Using + operator
result := str3 + " to " + str4
fmt.Println("New string 2: ", result)
}
New string 1: Hello Reader!
New string 2: Welcome to FreetimeLearning.com
for [condition | ( init; condition; increment ) | Range]
{
statement(s);
}
func function_name( [parameter list] ) [return_types]
{
body of the function
}
var x = 5
var p *int
p = &x
fmt.Printf("x = %d", *p)
Here x
can be accessed by *p
.​_test.go
and includes a TestXxx
function, where Xxx
is replaced with the name of the feature you’re testing. For example, a function that tests login capabilities would be called TestLogin
. go test
command.adder()
returns a closure, which is each bound to its own referenced sum variable.package main
import "fmt"
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
pos(i),
neg(-2*i),
)
}
}​
Output :
0 0
1 -2
3 -6
6 -12
10 -20
15 -30
21 -42
28 -56
36 -72
45 -90
type Animal struct {
// …
}
func (a *Animal) Eat() { … }
func (a *Animal) Sleep() { … }
func (a *Animal) Run() { … }
type Dog struct {
Animal
// …
}
Eat()
, Sleep()
, and Run()
functions. These functions are embedded into the child struct Dog by simply listing the struct at the top of the implementation of Dog.x =20, x
is an lvalue and 20
is an rvalue.10 = 20
is invalid because there is an rvalue (10
) left of the = operator.The sender will block on an unbuffered channel until the receiver receives data from the channel, and the receiver will block on the channel until the sender puts data into the channel.
The sender of the buffered channel will block when there is no empty slot on the channel, however, the receiver will block on the channel when it is empty, as opposed to the unbuffered equivalent.
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
}
45
package main
import "fmt"
func foo() (string, string) {
return "two", "values"
}
func main() {
fmt.Println(foo())
}​
Output : two values
package main
import "fmt"
func main() {
// Create
var stack []string
// Push
stack = append(stack, "world!")
stack = append(stack, "Hello ")
for len(stack) > 0 {
// Print top
n := len(stack) - 1
fmt.Print(stack[n])
// Pop
stack = stack[:n]
}
// Output: Hello world!
}​
Output :
Hello world!
First, we use the built-in append()
function to implement the append behavior. Then we use len(stack)-1
to select the top of the stack and print.
For pop, we set the new length of the stack to the position of the printed top value, len(stack)-1
.
perm()
function that accepts a slice or string and prints all possible combinations of characters.package main
import "fmt"
// Perm calls f with each permutation of a.
func Perm(a []rune, f func([]rune)) {
perm(a, f, 0)
}
// Permute the values at index i to len(a)-1.
func perm(a []rune, f func([]rune), i int) {
if i > len(a) {
f(a)
return
}
perm(a, f, i+1)
for j := i + 1; j < len(a); j++ {
a[i], a[j] = a[j], a[i]
perm(a, f, i+1)
a[i], a[j] = a[j], a[i]
}
}
func main() {
Perm([]rune("abc"), func(a []rune) {
fmt.Println(string(a))
})
}
abc
acb
bac
bca
cba
cab
map_name[key_name]
and we can check if the key, say “foo”, is present or not and then perform some operations by using the below code:if val, ok := dict["foo"]; ok {
//do something here
}
val
will receive either the value of "foo
" from the map or a "zero value" (in this case the empty string) and ok
will receive a bool that will be set to true
if "foo
" was actually present in the map if
statement will be executed and val
will be local to that scope./DemoStruct definition
type DemoStruct struct {
Val int
}
//A.
func demo_func() DemoStruct {
return DemoStruct{Val: 1}
}
//B.
func demo_func() *DemoStruct {
return &DemoStruct{}
}
//C.
func demo_func(s *DemoStruct) {
s.Val = 1
}
*DemoStruct
, which is a pointer to the struct, it returns a pointer to the struct value created within the function.Error()
method is considered as an error. Go does not have try/catch methods as in other programming languages for handling the errors. They are instead returned as normal values. Following is the syntax for creating the error interface:type error_name interface {
Error() string
}
switch optstatement; optexpression
{
case exp1: statement
case exp2: statement
…..
default: statement
}
switch optstatement; type switchexpression
{
case type1: statement
case type2: statement
…..
default: statement
}
package main
import "fmt"
func main() {
fmt.Println(swap())
}
func swap() []int {
a, b := 15, 10
b, a = a, b
return []int{a, b}
}
Output :
[10 15]
While this may be tricky in other languages, Go makes it easy.
We can simply include the statement b, a = a, b
, what data the variable references without engaging with either value.
Min(x, y int)
and Max(x, y int)
functions that take two integers and return the lesser or greater value, respectively.package main
import "fmt"
// Min returns the smaller of x or y.
func Min(x, y int) int {
if x > y {
return y
}
return x
}
// Max returns the larger of x or y.
func Max(x, y int) int {
if x < y {
return y
}
return x
}
func main() {
fmt.Println(Min(5,10))
fmt.Println(Max(5,10))
}​
Output :
5
10
var numOfCars = 2 // Line 1
type Car struct{
name string
model string
color string
}
cars:= [{
name:"Toyota",
model:"Corolla",
color:"red"
},
{
name:"Toyota",
model:"Innova",
color:"gray"
}]
func countRedCars(){
for i:=0; i<numOfCars; i++{
if cars[i].color == "red" {
numOfCars +=1 // Line 2
fmt.Println("Inside countRedCars method ", numOfCars) //Line 3
}
}
}
Line 1
comment. Inside the countRedCars method, we have an if statement that checks whether the colour is red and if red then increments the numOfCars by 1. The interesting point here is that the value of the numCars variable after the end of the if statement will not be affecting the value of the numOfCars variable in the outer scope.fib(0)=0
fib(1)=1
fib(2)=1+0 = 1
fib(3)=1+1 = 2
fib(4)=2+1 = 3
:
:
fib(n)=fib(n-1)+fib(n-2)
package main
import "fmt"
//nth fibonacci number function
func fibonacci(n int) int {
if n < 2 {
return n
}
return fibonacci(n-1) + fibonacci(n-2)
}
func main() {
fmt.Println(fibonacci(7))
}
13
fmt.Sprintf()
, which returns a string without printing it.package main
import "fmt"
func main() {
s := fmt.Sprintf("Size: %d MB.", 90)
fmt.Println(s)
}
Output :
Size: 90 MB.
// Golang program to show how
// to use command-line arguments
package main
import (
"fmt"
"os"
)
func main() {
// The first argument
// is always program name
myProgramName := os.Args[0]
// it will display
// the program name
fmt.Println(myProgramName)
}
Output : Here, you can see it is showing the program name with full path. Basically you can call this as Os Filepath output. If you will run the program with some dummy arguments then that will also print as a program name.
function function_name(para1, para2...type)type{
// code...
}​
type[]int
.// Go program to illustrate the
// concept of variadic function
package main
import(
"fmt"
"strings"
)
// Variadic function to join strings
func joinstr(element...string)string{
return strings.Join(element, "-")
}
func main() {
// zero argument
fmt.Println(joinstr())
// multiple arguments
fmt.Println(joinstr("FREE", "LEARN"))
fmt.Println(joinstr("Free", "Time", "Learn"))
fmt.Println(joinstr("F", "R", "E", "E"))
}
​
Output :
FREE-LEARN
Free-Time-Learn
F-R-E-E
Example 2 :
// Go program to illustrate the
// concept of variadic function
package main
import(
"fmt"
"strings"
)
// Variadic function to join strings
func joinstr(element...string)string{
return strings.Join(element, "-")
}
func main() {
// pass a slice in variadic function
element:= []string{"free", "TIME", "learn"}
fmt.Println(joinstr(element...))
}​
Output :
free-TIME-learn
variable_name := expression
// Go program to demonstrate the
// difference between = and :=
package main
import (
"fmt"
)
func main() {
// Simple declaration & assignment
var x int = 10
// Shorthand declaration
y := 20
// Printing the values and types of both
fmt.Printf("x = %T, %v\n", x, x)
fmt.Printf("y = %T, %v\n", y, y)
}
x = int, 10
y = int, 20
=
operator and the variable y is declared and assigned using the :=
operator. In the first case, the var keyword and type are required while in the second case, the var keyword and type are not required.// Go program to demonstrate the
// difference between = and :=
package main
import (
"fmt"
)
func main() {
// Declare & assign using :=
x, y, z := 10, 20, 30
// Printing the types and values
fmt.Printf("%T, %v\n", x, x)
fmt.Printf("%T, %v\n", y, y)
fmt.Printf("%T, %v\n", z, z)
// Updating the values using =
x, y, z = 100, 200, 300
// Printing the types and values
fmt.Printf("%T, %v\n", x, x)
fmt.Printf("%T, %v\n", y, y)
fmt.Printf("%T, %v\n", z, z)
}
int, 10
int, 20
int, 30
int, 100
int, 200
int, 300