Curated collection of useful Go snippets that you can understand in 30 seconds or less.
Note: The project is inspired by 30 seconds of code, but there is no affiliation with that project.
To install this package, you need to install Go and setup your Go workspace on your computer. The simplest way to install the library is to run:
$ go get -u github.com/thinkerou/30-seconds-of-go
This requires Go 1.12 or later.
View contents
View contents
View contents
View contents
View contents
View contents
View contents
View contents
Returns the average of two or more numbers.
Examples
Returns the average of an array, after mapping each element to a value using the provided function.
Examples
Geerates an array, containing the Fibonacci sequence, up until the nth term.
Examples
Calculates the greatest common divisor between two or more numbers/arrays.
Examples
Returns true
if the given number is even, false
otherwise.
Checks whether a number is odd or even using the modulo (%
) operator or and (&
) operator. Returns true
if the number is even, false
if the number is odd.
func isEven(i int) bool {
return i % 2 == 0
}
func isEven(i int) bool {
return i & 1 == 0
}
Examples
isEven(-1) // false
isEven(-2) // true
isEven(3) // false
isEven(4) // true
Returns true
is the given positive integer is the power of 2, false
otherwise.
Checks whether a positive integer is the power of 2 using the and (&
) operator.
func is PowerOf2(i uint) bool {
return i & (i -1) == 0
}
Examples
isPowerOf2(1) // true
isPowerOf2(2) // true
isPowerOf2(3) // false
isPowerOf2(4) // true
Checks if the provided integer is a prime number.
Check numbers from 2
to the square root of the given number. Return false
if any of them divides the given number, else return true
, unless the number is less than 2
.
func isPrime(n int) bool {
boundary := int (math.Floor(math.Sqrt(float64 (n))))
for i := 2; i <= boundary; i++ {
if n % i == 0 {
return false
}
}
return n >= 2
}
Examples
isPrime(0) // false
isPrime(1) // false
isPrime(2) // true
isPrime(3) // true
isPrime(4) // false
isPrime(11) // true