30-seconds-of-go

Curated collection of useful Go snippets you can understand in 30 seconds or less.

View on GitHub

30 seconds of Go

Build Status codecov Go Report Card GoDoc

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.

Installation

⚠️ NOTICE: A few of our snippets are not yet optimized for production (see disclaimers for individual snippet issues).

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

Prerequisites

This requires Go 1.12 or later.

Table of Contents

🔌 Adapter

View contents

📚 Array

View contents

⏱️ Date

View contents

🎛️ Function

View contents

➗ Math

View contents * [`average`](#average) * [`averageBy`](#averageby) * [`fibonacci`](#fibonacci) * [`gcd`](#gcd) * [`isEven`](#iseven) * [`isPowerOf2`](#ispowerof2) * [`isPrime`](#isprime)

🗃️ Object

View contents

📜 String

View contents

📃 Type

View contents

🔧 Utility

View contents

➗ Math

average

Returns the average of two or more numbers.

Examples ```go ```


⬆ Back to top

averageBy

Returns the average of an array, after mapping each element to a value using the provided function.

Examples ```go ```


⬆ Back to top

fibonacci

Geerates an array, containing the Fibonacci sequence, up until the nth term.

Examples ```go ```


⬆ Back to top

gcd

Calculates the greatest common divisor between two or more numbers/arrays.

Examples ```go ```


⬆ Back to top

isEven

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 ```


⬆ Back to top

isPowerOf2

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 ```


⬆ Back to top

isPrime

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 ```


⬆ Back to top