Go Interview Snippets
Slices
Reverse a Slice
numbers := []int{1, 2, 3, 4, 5}
reversedNumbers := make([]int, len(numbers))
for i, num := range numbers {
reversedNumbers[len(numbers)-1-i] = num
}
fmt.Println(reversedNumbers) // Output: [5 4 3 2 1]
Create a slice with initial values
var slice = []int{1, 2, 3, 4, 5}
fmt.Println(slice) // Output: [1 2 3 4 5]
Sort Slice
There are several approaches how we can sort slices based on it’s type: sort.Ints
, sort.Float64s
, sort.Strings
, sort.Slice
.
Here is the example of sort.Ints
:
numbers := []int{5, 2, 6, 3, 1, 4}
sort.Ints(numbers)
fmt.Println(numbers)
// Output: [1 2 3 4 5 6]
Arrays
Create an array with initial values
var arr [5]int = [5]int{1, 2, 3, 4, 5}
Sort Array
String
Capitalize a String
str := "hello"
capitalizedStr := strings.Title(str)
fmt.Println(capitalizedStr) // Output: "Hello"
Reverse a String
str := "Hello"
reversedStr := ""
for i := len(str) - 1; i >= 0; i-- {
reversedStr += string(str[i])
}
fmt.Println(reversedStr) // Output: "olleH"
Check if a String is a Palindrome
func isPalindrome(s string) bool {
for i := 0; i < len(s)/2; i++ {
if s[i] != s[len(s)-1-i] {
return false
}
}
return true
}
Sort String
str := "hello"
sortedStr := strings.Join(strings.Split(str, ""), "")
fmt.Println(sortedStr) // Output: "ehllo"
Count Characters in a String
str := "hello"
charCount := make(map[rune]int)
for _, char := range str {
charCount[char]++
}
fmt.Println(charCount)
// Output: map[97:1 104:1 108:2 111:1]
Check is String a Number
str := "10"
fmt.Println(str) // Output: "10"
From String to Number
str := "10"
num, err := strconv.Atoi(str)
if err != nil {
fmt.Println(err)
}
fmt.Println(num) // Output: 10
Conversions
From String to Number
str := "10"
num, err := strconv.Atoi(str)
if err != nil {
fmt.Println(err)
}
fmt.Println(num) // Output: 10
From Number to String
num := 10
str := strconv.Itoa(num)
fmt.Println(str) // Output: "10"
Ascii values
- From char to ascii
char := 'A'
asciiVal := int(char)
fmt.Println(asciiVal) // Output: 65
- From Ascii to char
asciiVal := 65
char := rune(asciiVal)
fmt.Println(char) // Output: "A"
Structs
Create a Struct
type Person struct {
Name string
Age int
}
person := Person{
Name: "John",
Age: 30,
}
fmt.Println(person) // Output: {John 30}