Golang : Generate universally unique identifier(UUID) example
A UUID ( universally unique identifier ) is a 128-bit string value that is used in developing software. An example of UUID string looks like :
69cda7b3-9a67-47ce-beac-16ce1dc177e0
UUID is commonly used in generating MAC addresses for network interface hardware devices, primary keys identifiers in database to ensure uniqueness in a cluster of database servers and also use in binding registration serial number of shareware/licensed software to customer's computers. In some computer games, UUID is generated on the fly as a way identify objects in the virtual world.
Here are two examples of generating UUID in Golang.
To generate UUID with https://github.com/pborman/uuid
example :
package main
import (
"fmt"
"github.com/pborman/uuid"
)
func main() {
uuid := uuid.New()
fmt.Println(uuid)
}
Sample output :
69cda7b3-9a67-47ce-beac-16ce1dc177e0
and for time based UUID generation example :
package main
import (
"crypto/rand"
"fmt"
"time"
)
func main() {
// generate 32 bits timestamp
unix32bits := uint32(time.Now().UTC().Unix())
buff := make([]byte, 12)
numRead, err := rand.Read(buff)
if numRead != len(buff) || err != nil {
panic(err)
}
fmt.Printf("%x-%x-%x-%x-%x-%x\n", unix32bits, buff[0:2], buff[2:4], buff[4:6], buff[6:8], buff[8:])
}
Sample output :
564e9408-fb78-4856-4215-52e0-e14bb054
References :
https://en.wikipedia.org/wiki/Universallyuniqueidentifier
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.1k Golang : error parsing regexp: invalid or unsupported Perl syntax
+8k Golang : Generate random Chinese, Japanese, Korean and other runes
+7k Golang : HttpRouter multiplexer routing example
+9.1k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+4.4k Golang : Generate Interleaved 2 inch by 5 inch barcode
+16.1k Golang : Find smallest number in array
+4.9k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+9.3k JavaScript/JQuery : Detect or intercept enter key pressed example
+4.2k Golang *File points to a file or directory ?
+4.9k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+15.3k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+10.3k Golang : Display a text file line by line with line number example