func 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]
}
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)
}
package main
import (
"fmt"
"time"
)
func main() {
go sampleRoutine()
fmt.Println("Started Main")
time.Sleep(1 * time.Second)
fmt.Println("Finished Main")
}
func sampleRoutine() {
fmt.Println("Inside Sample Goroutine")
}
Started Main
Inside Sample Goroutine
Finished Main
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 := "Educative.io"
// Concatenating strings
// Using + operator
result := str3 + " to " + str4
fmt.Println("New string 2: ", result)
}
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),
)
}
}
type Animal struct {
// …
}
unc (a *Animal) Eat() { … }
func (a *Animal) Sleep() { … }
func (a *Animal) Run() { … }
type Dog struct {
Animal
// …
}
{
name string
Rollno int
address string
}
//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
}