Jump to content

Search the Community

Showing results for tags 'golang'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • General
    • General Discussion
    • Artificial Intelligence
    • DevOpsForum News
  • DevOps & SRE
    • DevOps & SRE General Discussion
    • Databases, Data Engineering & Data Science
    • Development & Programming
    • CI/CD, GitOps, Orchestration & Scheduling
    • Docker, Containers, Microservices, Serverless & Virtualization
    • Infrastructure-as-Code
    • Kubernetes & Container Orchestration
    • Linux
    • Logging, Monitoring & Observability
    • Security, Governance, Risk & Compliance
  • Cloud Providers
    • Amazon Web Services
    • Google Cloud Platform
    • Microsoft Azure

Calendars

  • DevOps Events

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


LinkedIn Profile URL


About Me


Cloud Platforms


Cloud Experience


Development Experience


Current Role


Skills


Certifications


Favourite Tools


Interests

Found 9 results

  1. Golang and Rust are two modern programming languages that have gained significant popularity in recent years. In the Stack Overflow Developer Survey 2023, developers voted Rust as the most admired language. An impressive 84.66% of developers surveyed expressed their intention to use Rust in the coming year. Golang also received significant admiration, with 62.45% of developers showing interest in using it. In this blog post, we’ll provide a comprehensive comparison between Golang and Rust. We will dive into various aspects of these languages, including their background, language features, use cases, ecosystem, and learning curve. Whether you’re considering which language to learn next, deciding on the right tool for a new project, or simply curious about what each language has to offer, this post will help you make informed choices. Let’s get started! Background: Golang vs. RustGolang was created at Google by Rob Pike, Ken Thompson, and Robert Griesemer. It was started in 2007 as an internal project to address the challenges Google faced with its existing programming languages. The designers aimed to create a language that combined the efficiency and safety of statically typed languages with the simplicity and ease of use of dynamically typed languages. Golang was officially announced as an open-source project in 2009, with version 1.0 released in March 2012. In contrast, Rust was initially developed as a side project by Graydon Hoare while working at Mozilla Research. It was later officially sponsored by Mozilla in 2009. The first stable release of Rust arrived in May 2015. Rust was designed to be a safe alternative to C++, which is widely used in systems programming but is prone to memory-related bugs and security vulnerabilities. Key Language Features: Golang vs. RustIn this section, we’ll explore the key features that have contributed to Golang’s and Rust’s popularity among developers. Golang language featuresThe most significant features of the Golang programming language are as follows: Statically typed: Golang is a statically typed language, meaning that variable types are checked at compile time. This helps catch type-related errors early in the development process, leading to more robust and reliable code.High-speed compilation: Golang has a fast compiler that uses a simplified dependency resolution algorithm. When you build a Golang program, the compiler leverages the compilation cache to intelligently manage and build only the required dependencies. This contributes to faster compilation time compared to other languages such as C++ or Java. Built-in concurrency support: Golang provides built-in support for concurrency through goroutines and channels. Goroutines are lightweight threads managed by the Go runtime, allowing multiple functions to run concurrently. Channels provide a way for goroutines to communicate and synchronize with each other. This built-in concurrency support enables developers to write efficient, high-performance applications that can handle multiple tasks simultaneously. Built-in garbage collector: Golang has a built-in garbage collector that automatically manages memory allocation and deallocation. It frees developers from the need to manually manage memory, preventing memory leaks and other memory-related bugs. Moreover, the garbage collector runs concurrently with the program execution, minimizing performance impact.Rust language featuresMoving onto Rust, let's explore the key features that set this programming language apart: Statically typed with type inference: Rust is also a statically typed language, ensuring that types are checked at compile time. Rust goes a step further with a type inference system that can deduce the types of variables based on their usage. This provides the benefits of static typing, such as early error detection and improved performance, while reducing the verbosity of the code.Ahead-of-time compilation: Rust is an ahead-of-time (AOT) compiled language, which means that the code is compiled directly to machine code before execution. This results in fast and efficient binaries that can be deployed without the need for a runtime environment. AOT compilation also enables Rust to catch many errors at compile-time, providing early feedback and reducing the chances of runtime errors.Robust concurrency: Rust's ownership system and type system guarantee thread safety, preventing common concurrency issues like data races and deadlocks. Rust provides several primitives for concurrent programming, such as threads, channels, and locks, which can be used safely without introducing runtime overhead. This allows developers to write efficient and correct concurrent code with confidence.Ownership and borrowing: Rust has a unique ownership system that ensures memory safety at compile time. Each value in Rust has an owner, and there can only be one owner at a time. Rust also has a borrowing system that allows you to reference data without taking ownership. This system prevents common issues like null or dangling pointer dereferences, data races, and memory leaks.Common Use Cases: Golang vs. RustGolang and Rust have distinct strengths that make them suitable for different use cases. In the following sections, we'll explore the key areas where each language excels. Golang use casesAlthough Golang is a general-purpose programming language, its primary use cases are as follows: Cloud and network services: Golang's built-in concurrency features, like goroutines and channels, make it ideal for handling many concurrent requests in cloud environments. This allows Golang to deliver high performance and low latency, which is critical for cloud services.Servers built with Golang have instant start-up times and lower memory and CPU utilization compared to other languages. This makes Golang applications cheaper to run in serverless deployments on cloud platforms. In addition, Go has a robust ecosystem for cloud development. Major cloud providers like GCP, AWS, and Azure offer Golang SDKs for their services. Popular open-source projects for cloud-native development, like Docker and Kubernetes, are built using Golang. Command line interfaces: Golang is an ideal language for CLI development due to its fast compile times, allowing programs to start quickly. Golang compiles into a single binary that can run on any system without requiring external libraries or dependencies, making installation and distribution trivial.Web development: Golang delivers excellent out-of-the-box performance, making it easy to build fast and scalable web applications. It has an excellent standard library for web development, including packages for HTTP servers, routing, templating, encryption, and more. The Golang community has also built web frameworks like Gin, Echo, Revel, and Beego that provide additional functionality and productivity.Development Operations (DevOps) and Site Reliability Engineering (SRE): Golang's fast build times and lean syntax enable rapid development of DevOps and SRE tools. This allows teams to quickly create and iterate on automation scripts, CLIs, and services. Popular DevOps tools like Docker, Kubernetes, and Terraform are built using Golang, which integrates well with cloud platforms and CI/CD systems, making it suitable for modern DevOps practices.Rust use casesRust’s key strength lies in systems programming and low-level development. Let’s explore some of its most common use cases: Command line applications: Rust's performance and low-level control make it an excellent choice for building efficient command line applications. Rust's compile time error checking and memory safety features help prevent common bugs and vulnerabilities. Its ability to compile to a single binary without external dependencies simplifies the distribution and deployment of CLI tools.Browser-native libraries through WebAssembly: Rust can be compiled to WebAssembly (Wasm), allowing developers to write performance-critical code in Rust and run it in web browsers. This enables building browser-native libraries and applications with near-native performance.Rust's memory safety makes it well-suited for Wasm development. Its toolchain provides excellent support for Wasm, enabling seamless interoperability between Rust and JavaScript. Microcontrollers and embedded systems: Rust's low-level control and memory efficiency make it an ideal language for microcontrollers and embedded systems. Its ownership system and borrow checker help prevent common issues like buffer overflows, which are critical in resource-constrained environments.Rust provides a rich ecosystem for embedded development, including libraries for hardware abstraction and architecture-specific support. Its cross-compilation capabilities make it easy to target different embedded platforms. Network services: Rust's performance, concurrency features, and memory safety make it well-suited for building high-performance network services. Its ownership system and borrow checker help prevent common concurrency bugs.Rust provides a robust ecosystem for network programming, including libraries for asynchronous I/O, HTTP, and gRPC. Its async/await syntax enables writing efficient and scalable network services. Ecosystem and Community: Golang vs. RustBoth Golang and Rust benefit from robust ecosystems and engaged communities, crucial for the success and growth of any programming language. Golang’s ecosystem and communityGolang has a comprehensive standard library and a rich ecosystem of third-party packages and frameworks that cover various domains, such as web development, database connectivity, logging, testing, and more. Golang also has an active and growing community of developers worldwide. It has a strong presence on platforms like GitHub, Stack Overflow, and Reddit, where developers actively contribute to open-source projects, share knowledge, and engage in discussions. Moreover, Golang has gained significant adoption by major companies and organizations such as Cloudflare, Dropbox, Google Cloud, IBM, Microsoft, Netflix, Stripe, Twitch, Uber and YouTube. The adoption of Golang by major companies demonstrates its reliability, scalability, and suitability for building large-scale systems. Rust's ecosystem and communitySimilarly, Rust has a growing package ecosystem centered around Cargo, its official package manager. The Rust package registry, crates.io, hosts a wide variety of packages contributed by the community. These packages cover various domains, including command-line utilities, embedded development, network programming, web development, and more. The Rust ecosystem is actively expanding, with new packages and frameworks being developed and shared by the community. In addition to its growing ecosystem, Rust benefits from a supportive and inclusive community. The language has a strong presence on platforms like GitHub, Reddit, and Discord, where developers actively engage in discussions, share knowledge, and collaborate on projects. Rust has caught the attention of major companies and organizations. Mozilla, the creator of Rust, uses it in their Servo web browser engine and parts of the Firefox browser. Microsoft has been exploring the use of Rust for secure systems programming and has been actively contributing to the Rust community. Other companies using Rust include Cloudflare, Discord, Figma, and npm. Learning Curve: Golang vs. RustGolang focuses on simplicity and readability, with a straightforward syntax that is easy to understand. Its simplicity makes Golang relatively quick to learn compared to many other languages. Developers from various backgrounds can pick up Golang without too much difficulty. To get started learning Golang, check out KodeKloud’s Golang course. In contrast, Rust has a steeper learning curve compared to Golang. This is largely due to Rust's unique concepts, such as ownership, borrowing, and lifetimes. Fully grasping and correctly applying these concepts takes time and practice for many developers. However, while Rust's learning curve may be steeper initially, it rewards developers with a powerful type system, built-in memory safety, and fine-grained control over system resources. Once comfortable with its core concepts and idioms, you can leverage its safety and performance benefits to build robust and efficient software systems. ConclusionGolang and Rust are both powerful languages with distinct strengths. As you explore these languages further, you'll discover their potential to revolutionize how you build software. Read about the top 10 programming languages in 2023 in our blog post: Top 10 Programming Languages in 2023. Starting from scratch in programming? Check out KodeKloud’s Programming Learning Path, which provides a structured approach to mastering programming skills. View the full article
  2. Golang which is also called Go programming language is an open-source programming language designed by Google in 2007. Version 1.0 of this language was released in 2012. It is a structured programming language like C and different types of applications such as networking services, cloud applications, web applications, etc. can be developed by Golang language. It contains many types of packages like Python. It is very easy to learn, which makes this language popular for new programmers. 30 Golang programming examples have been explained in this tutorial to learn Golang from the basics. Pre-requisites: Golang is supported by different types of operating systems. The way of installing Golang on Ubuntu has been shown in this part of the tutorial. Run the following commands to update the system and install the Golang on the system before practicing the examples in this tutorial. $ sudo apt update $ sudo apt install golang-go Run the following command to check the installed version of the Golang. $ go version Table of contents: Golang hello world Golang string variables Golang int to string Golang string to int Golang string concatenation Golang multiline string Golang split string Golang sprintf Golang enum Golang struct Golang array Golang set Golang for loop Golang for range Golang while loop Golang continue Golang switch case Golang random number Golang sleep Golang time Golang uuid Golang read file Golang read file line by line Golang write to file Golang check if file exists Golang csv Golang yaml Golang http request Golang command line arguments Golang error handling Golang hello world The main package of Golang contains all required packages for Golang programming and it is required to start the execution of the Golang script. The fmt package is required to import for printing the formatted string in the terminal. Create a Golang file with the following script. The string value, ‘Hello World.’ will be printed in the terminal after executing the script. //Import the fmt package to print the output import "fmt" //Define the main() function to start the execution func main() { //Print a simple message with the new line fmt.Println("Hello World.") } Run the following command to execute the script. Here, the script has been saved in the example1, go file. $ go run example1.go Run the following command to build the binary file of the Golang file. $ go build example1.go Run the following command to run the executable file. $ ./example1 The following output will appear after executing the above commands,, Go to top Golang string variables The string variables can be used without defining the data type and with the data type in Golang. Create a Golang file with the following script that will print simple string data and the string data with the string variables. The uses of Printf() and Println() functions have been shown in the script. package main //Import the fmt package to print the output import "fmt" //Define the main() function func main() { //Print a string value with a new line fmt.Printf("Learn Golang from LinuxHint.com.\n") //Define the first string variable var str1 = "Golang Programming. " //Print the variable without a newline fmt.Printf("Learn %s", str1) //Define the second string variable var str2 = "easy to learn." //Print the variable with a newline fmt.Println("It is", str2) } The following output will appear after executing the above script. The output of the two concatenated strings are printed here. Go to top Golang int to string The strconv.Itoa() and strconv.FormatInt() functions can be used to convert the integer to a string value in Golang. The strconv.Itoa() is used to convert the integer value into a string of numbers. The strconv.FormatInt() function is used to convert decimal-based integer values into the string. Create a Golang file with the following script that shows the way of converting the integer to a string in Golang by using the functions mentioned above. A number will be taken from the user and the corresponding string value of the number will be printed as the output. //Add the main package package main //Import the fmt and strconv packages import ( "fmt" "strconv" ) //Define the main function func main() { //Declare an integer variable var n int //Print a message fmt.Printf("Enter a number: ") //Take input from the user fmt.Scan(&n) //Convert integer to string using Itoa() function convert1 := strconv.Itoa(n) fmt.Printf("Converting integer to string using Itoa(): %s\n", convert1) //Convert integer to string using FormatInt() function convert2 := strconv.FormatInt(int64(n), 10) fmt.Printf("Converting integer to string using FormatInt(): %s\n", convert2) } The following output will appear after executing the script. The number. 45 has been converted to the string. “45”. Go to top Golang string to int The strconv.Atoi() function is used to convert the string to an integer in Golang. It takes a string value that will be converted into an integer and returns two types of values. One value is the integer if the conversation is successful and another value is the error if the conversation is unsuccessful otherwise nil value will be returned. Create a Golang file with the following script that will convert a number of string values into an integer by using strconv.Atoi() function. The string value, “342” will be converted into 342 number and printed after the execution. //Add the main package package main //Import the fmt and strconv packages import ( "fmt" "strconv" ) //Define the main function func main() { //Declare a string variable str := "342" //Convert string to integer using Atoi() function price, err := strconv.Atoi(str) //check for error if err == nil { //Print the converted value fmt.Printf("The price of the book is %d\n", price) }else{ //Print the error message fmt.Println(err) } } The following output will appear after executing the script. The string value, “342” has been converted to 342 here. Go to top Golang string concatenation Create a Golang file with the following script that will concatenate the strings with the ‘+’ operator by using the Printf() function. The Println() function has been used here to print the concatenated string value by using the ‘+’ operator and Printf() function has been used here to print the concatenated string value by using the ‘%s’ specifier. Two string variables have been declared in the script which are concatenated later. //Add the main package package main //Import the fmt package to print the output import "fmt" //Define the main function func main() { //Declare two string variables var str1, str2 string //Assign string values str1 = " Golang" str2 = " Programming" //Concatenating string using '+' operator fmt.Println("Concatenated string value using '+' operator:", str1 + str2) //Concatenating string using '%s' specifier fmt.Printf("Concatenated string value using format specifier: %s%s\n", str1, str2) } The following output will appear after executing the script. Go to top Golang multi-line string Three different ways have been shown in the following example to print the multi-line text by using the Golang script. The ‘\n’ character has been used in the first string variable to generate the multi-line text. The backticks (`) have been used in the second string to print the multi-line text. The backticks (`) with specifiers have been used in the third string to print multi-line text. package main //Import the fmt package import "fmt" //Define the main function func main() { //Declare a multi-line string value with '\n' character str1 := "Golang programming\is very easy\nto learn.\n\n" fmt.Printf(str1) //Declare a multi-line string value with backticks(`) str2 := `Learn Golang from LinuxHint Blog.` fmt.Printf("%s\n\n",str2) //Declare two string values language := "Golang" developer := "Google" //Declare a string value with variables and backticks str3 := `%s is developed by %s.` fmt.Printf(str3, language, developer) //Add a new line fmt.Println() } The following output will appear after executing the script. The output of the three string variables that contain multi-line string values has been printed here. Go to top Golang split string The strings.Split() function has been used to split the string data based on the separator. The following script will take a string value from the user and split the string value based on the colon(:). The total number of split values and the first two split values will be printed after the execution. package main //Import the fmt and strings packages import ( "fmt" "strings" ) //Define the main function func main() { //Declare a string variable var str string //Print a prompt message fmt.Printf("Enter a string with colon(:)- ") //Take input from the user fmt.Scan(&str) //Define the separator separator := ":" //Split the string value split_value := strings.Split(str, separator) //Count the number of split values length := len(split_value) //Print the number of split values fmt.Printf("Total number of split values is %d\n", length) //Print the split values fmt.Println("The first split value is", split_value[0]) fmt.Println("The second split value is", split_value[1]) } The following output will appear after executing the script. The input value, “golang:google” has been divided into two parts based on the colon(:). Go to top Golang sprintf The Sprintf() function is used in Golang to store the formatted string values into a variable like other standard programming languages. A string and an integer variable have been declared in the following script. The values of these variables have been formatted and stored into a variable by using the Sprintf() function. package main //Import the fmt package import "fmt" //Define the main function func main() { //Declare two variables var str string var num int //Assign string value str = "Golang" //Assign number value num = 2012 //Store the combined string value in a variable combined_str := fmt.Sprintf("The first version of %s is released in %d.", str, num) //Print the variable fmt.Printf("The output of the Sprintf(): \n%s\n", combined_str) } The following output will appear after executing the script. Go to top Golang enum The enum or enumerator has been used in Golang to declare a data type of a group of related constant values. The declaration of enum type in Golang is different from other programming languages. An enum type of 12 values has been declared and the numeric value of the particular enum value has been printed later. package main //Import the fmt package import "fmt" //Declare the type to store the month value in number (1-12) type Month int //Declare constants for each month's value starting from 1 const ( Jan Month = iota + 1 Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ) //Declare main function func main() { //Declare variable with a month value var M_num = May //Print the corresponding number value of the month fmt.Println("The month value in number is ", M_num) } The following output will appear after executing the script. The corresponding numeric value of the May is 5. Go to top Golang struct The struct or structure is used in Golang to declare a type that contains different types of variables. It is useful for storing tabular data or multiple records. In the following script, a structure variable of four elements has been declared. Next, two records have been added by using the defined struct variable. The way of printing the values of the struct in different ways has been shown in the last part of the script. package main //Import fmt package import "fmt" //Define a structure of four elements type Product struct { id string name string size string price int } func main() { //Declare the first structure variable product1 := Product {"p-1209", "HDD", "5TB", 80} //Declare the second structure variable product2 := Product {"p-7342", "Mouse", "", 15} //Print the structure variables fmt.Println("First product: ", product1) fmt.Println("Second product: ", product2) //Print four values of the first structure variable separately fmt.Println("First product details:") fmt.Println("ID: ",product1.id) fmt.Println("Name: ",product1.name) fmt.Println("Size: ",product1.size) fmt.Println("Price: ",product1.price) } The following output will appear after executing the script. Go to top Golang array The array variable is used in Golang to store multiple values of the particular data type like other standard programming languages. The way of declaring and accessing an array of string values and an array of numeric values has been shown in the script. package main //Import fmt package import "fmt" func main() { //Declare an array of string values str_arr := [4] string {"google.com", "ask.com", "bing.com", "you.com"} //Print the array of string fmt.Println("String Array values are: ", str_arr) //Print the 3rd element of the array fmt.Println("The 3rd value of array is", str_arr[2]) //Declare an array of numeric values int_arr := [6]int{65, 34, 12, 81, 52, 70} //Print the array of integer fmt.Println("Integer Array values are: ", int_arr) //Print the 4th element of the array fmt.Println("The 4th value of array is", int_arr[3]) } The following output will appear after executing the script. Go to top Golang set The set is another data structure of Golang to store a collection of distinct values. It is used to store unique values in an object. Golang has no built-in set data structure like other programming languages. But this feature can be implemented by using empty struct{} and map. In the following script, a set variable of strings has been declared by using a map with the empty struct. Next, three values have been added, one value has been deleted, and one value has been added again in the set. The values of the set have been printed together and separately. package main //Import fmt package import "fmt" func main() { //Define a set of strings lang := map[string]struct{}{} //Insert three elements into the set using an empty struct lang["Go"] = struct{}{} lang["Bash"] = struct{}{} lang["Python"] = struct{}{} //Print the current existing elements of the set fmt.Println(lang) //Remove an element from the set delete(lang, "Python") //Add a new element to the set lang["Java"] = struct{}{} //Print the set values after removing and adding an element fmt.Println(lang) fmt.Printf("\nSet values are:\n") //Print each element of the set separately for l := range lang { fmt.Println(l) } } The following output will appear after executing the script. Go to top Golang for loop The for loop can be used in different ways and for different purposes in Golang. The use of three expressions for loop has been shown in the following script. The loop will be iterated 5 times to take 5 input values and the sum of these input values will be printed later. package main //Import fmt package import "fmt" func main() { //Declare an integer variable var number int //Declare a variable to store the sum value var sum = 0 //Define a for loop for n := 1; n <= 5; n++ { //Print a prompt message fmt.Printf("Enter a number:") //Take input from the user fmt.Scan(&number) //Add the input number with the sum variable sum = sum + number } //Print the summation result fmt.Printf("The sum of five input values is %d\n", sum) } The following output will appear after executing the script. The sum of 6, 3, 4, 7, and 9 is 29. Go to top Golang for range The range is used with the for loop in the Golang to access string, array, and map. The way of accessing an array of strings by using a for loop with range has been shown in the following script. The first for loop will print the array values only and the second for loop will print the indexes and values of the array. package main //Import fmt package import "fmt" func main() { //Declare an array of string flowers := [4] string {"Rose", "Lily", "Dalia", "Sun Flower"} fmt.Println("Array values are:") //Print the array values for _, val := range flowers { fmt.Println(val) } fmt.Println("Array indexes and values are:") //Print the array values based on index for in, val := range flowers { fmt.Printf("%d := %s\n", in + 1, val) } } The following output will appear after executing the script. Go to top Golang while loop Golang has no while loop like other programming languages. However, the feature of the while loop can be implemented in Golang by using the for loop. The way of implementing a while loop by using a for loop has been shown in the following script. The for loop will be iterated for 4 times and take four numbers. The sum of these numbers with the fractional value will be printed later. package main //Import fmt package import "fmt" func main() { counter := 1 sum := 0.0 var number float64 for counter <= 4 { //Print a prompt message fmt.Printf("Enter a number: ") //Take input from the user fmt.Scan(&number) //Add the input number with the sum variable sum = sum + number //Increment the counter by 1 counter++ } //Print the summation result fmt.Printf("The sum of four input values is %0.2f\n", sum) } The following output will appear after executing the script. The sum of 6.8, 3.2, 8.5, and 4.9 is 23.40. Go to top Golang continue The continue statement is used in any loop to omit the particular statements based on a condition. In the following script, the for loop has been used to iterate the loop that will omit the values of the 2nd and the fourth values of the array by using the continue statement. package main //Import fmt package import "fmt" func main() { counter := 1 sum := 0.0 var number float64 for counter <= 4 { //Print a prompt message fmt.Printf("Enter a number: ") //Take input from the user fmt.Scan(&number) //Add the input number with the sum variable sum = sum + number //Increment the counter by 1 counter++ } //Print the summation result fmt.Printf("The sum of four input values is %0.2f\n", sum) } The following output will appear after executing the script. Go to top Golang switch case The switch-case statement in Golang is similar to the other programming languages but no break statement is required with each case statement in Golang. The way of defining multiple case values inside the switch block has been shown in the following example. package main //Import fmt package import "fmt" func main() { var n int //Print a prompt message fmt.Printf("Enter the month value in number: ") //Take input from the user fmt.Scan(&n) //Print message based on the matching case value switch n { case 1, 2, 3, 4: fmt.Println("Winter semester.") case 5, 6, 7, 8: fmt.Println("Summer semester.") case 9, 10, 11, 12: fmt.Println("Fall Semester.") default: fmt.Println("Month value is out of range.") } } The following output will appear after executing the script. Go to top Golang random number The math/rand package has been used in Golang to generate random numbers. The way of generating four types of random numbers has been shown in the following script. The rand.Int() function is used to generate a long integer random number. The rand.Intn(n) function is used to generate an integer random number of the particular range and the highest value will be passed as the argument value of the function. The 999 is set as the argument value in the script. The rand.Float32() function is used to generate a short fractional random number and the rand.Float64() function is used to generate a long fractional random number. //Add main package package main //Import required modules import ( "fmt" "time" "math/rand" ) func main() { //Set seed to generate a random number rand.Seed(time.Now().UnixNano()) //Print generated random integer fmt.Println("Random integer value: ", rand.Int()) //Print the random integer within 999 fmt.Println("Random integer value with range: ", rand.Intn(999)) //Print the random 32 bits float fmt.Println("Random 32 bits float value: ", rand.Float32()) //Print the random 64 bits float fmt.Println("Random 64 bits float value: ", rand.Float64()) } The following output will appear after executing the script. Go to top Golang sleep The time.Sleep() function is used in Golang to pause the execution of the script for a certain period. The following script will calculate the average of three numbers and wait for 3 seconds before terminating the script. //Add main package package main //Import required packages import ( "fmt" "time" ) func main() { fmt.Println("Start executing the script...") //Define three variables a := 40 b := 30 c := 29 //Print the variables fmt.Printf("Three numbers are : %d, %d, %d\n", a, b, c) fmt.Println("Calculating the average of three numbers...") avg := (a + b + c)/3 //Delay for 3 seconds time.Sleep(3 * time.Second) //Print the results fmt.Printf("The average value is %d\n", avg) fmt.Println("Program terminated.") } The following output will appear after executing the script. Go to top Golang time The time package is used in Golang to read the current date and time. This package has many methods and properties to read the date and time in different ways. The date and time, ‘Mon Jan 2 15:04:05 -0700 MST 2006’ is used as the reference value in Golang to access the date and time. The uses of the time package have been shown in the following example. package main //Import required packages import ( "fmt" "time" ) func main() { //Read the current date and time today := time.Now() //Print the current date fmt.Printf("Today is %s.\n", today.Format("02-Jan-2006")) //Print the current date and time fmt.Printf("The current date and time is %s\n.", today.Format(time.RFC1123)) } The following output will appear after executing the script. Go to top Golang uuid The UUID or Universally Unique Identifier can be generated by Golang script. It is a 128-bit unique value to identify the computer system. You have to download the uuid from the github.com/google/uuid before executing the following script. Go to the home directory and run the following commands to download the required package to generate the uuid by Golang script. $ go mod init uuid $ go get github.com/google/uuid In the following script, the first uuid is generated by using the uuid.New() function that returns a unique identifier. The second uuid is generated by the uuid.NewUUID() function that returns two values. The value contains the unique identifier and the second value contains the error message if it exists. package main //Import required packages import ( "fmt" "github.com/google/uuid" ) func main() { //Generate a unique ID using New() function newID := uuid.New() fmt.Printf("Generated first UUID is %s.\n", newID) //Generate a unique ID using NewUUID() function newID, err := uuid.NewUUID() //Check for error if err == nil { fmt.Printf("Generated second UUID is %s.\n", newID) }else{ fmt.Println(err) } } The following output will appear after executing the script. Go to top Golang read file The io/ioutil package of Golang is used to read the content of a file. The ReadFile() function of this package reads the whole content of a file. This function returns the full content of the file into a variable if the file exists otherwise an error message will be returned. The way of reading the full content of an existing text file has been shown in the following script. //Add main package package main //Import required packages import ( "io/ioutil" "fmt" "log" ) func main() { //Read a text file text, err := ioutil.ReadFile("Languages.txt") //Check for error if err == nil { fmt.Printf("Content of the file:\n\n") fmt.Println(string(text)) }else{ log.Fatalf("File read error: %v", err) } } The following output will appear after executing the script. Go to top Golang read file line by line The “bufio” package of Golang is used to read the content of a file line by line. In the following script, the bufio.NewScanner() has been used to create an object to read the file. Next, the Scan() function has been used with the loop to read and print each line of the file. //Add main package package main //Import required packages import ( "fmt" "os" "bufio" ) func main() { //Open a text file for reading fh, err := os.Open("Languages.txt") //Check for error if err == nil { //Scan the file content read := bufio.NewScanner(fh) //Read the file line by line for read.Scan() { fmt.Println(read.Text()) } }else{ fmt.Println(err) } //Close the file defer fh.Close() } The following output will appear after executing the script. Go to top Golang write to file The os package of the Golang is used to open a file for writing and the WriteString() function is used to write content into a file. The way of creating and writing a text file of three lines is by using the os package. package main //Import required packages import ( "fmt" "os" ) func main() { //Open a file for writing fh, err1 := os.Create("items.txt") //Check for file creation error if err1 == nil { //Write into the file _, err2 := fh.WriteString("Pen\nPencil\nRuler\n") //Check for file writing error if err2 != nil { fmt.Println("File write error occurred.\n") } }else{ fmt.Println("File creation error occurred.\n") } //Close the file defer fh.Close() } The following output will appear after executing the script. The output shows that the items.txt file has been created successfully. Go to top Golang checks if file exists The os package of the Golang can be used to check the existence of the file. In the following script, the file path will be taken from the script. If the path does not exist then the os.State() function will return an os.ErrNotExist error. package main //Import required module import ( "errors" "fmt" "os" ) func main() { var filepath string fmt.Printf("Enter an existing filename: ") //Take the file path from the user fmt.Scan(&filepath) //Check the file path _, error := os.Stat(filepath) //Check the output of the os.Stat if !errors.Is(error, os.ErrNotExist) { fmt.Println("File is found.") } else { fmt.Println("File is not found.") } } The following output will appear after executing the script. Go to top Golang csv The “encoding/csv” package is used in Golang to read the content of the CSV file. The csv.NewReader() function is used to read the CSV file. Create a CSV file before executing the script of this example. Here, the customers.csv file has been used to show the way of reading the CSV file. package main //Import required packages import ( "encoding/csv" "fmt" "os" ) func main() { //Open a CSV file for reading fh, err := os.Open("customers.csv") //Check for the error if err != nil { fmt.Println(err) }else{ //Create an object to read the CSV file scanner := csv.NewReader(fh) //Read all records of the CSV file records, _ := scanner.ReadAll() //Read the CSV file line by line for _, r := range records { for _, c := range r { fmt.Printf("%s,", c) } fmt.Println() } } //Close the file defer fh.Close() } The following output will appear after executing the script. Go to top Golang yaml The yaml.Marshal() function is used in Golang to read the content of the yaml data. You have to download the yaml package to use the yaml.Marshal(). Go to the home directory and run the following command to download the yaml package. $ go get <a href="http://gopkg.in/yaml.v2">gopkg.in/yaml.v2</a> In the following script, a structure variable of four elements has been declared that has been used later to define a yaml object with data. Next, the yaml.Marshal() function has been used to access the yaml data. package main //Import required packages import ( "fmt" "gopkg.in/yaml.v2" ) //Declare a structure of 4 elements type Book struct { Title string Author string Publication string Price string } func main() { //Create an object of the structure book1 := Book{ Title: "Learning Go", Author: "John Bodner", Publication: "O'Relly", Price: "$39", } //Read the yaml data based on the struct y_data, err := yaml.Marshal(&book1) //Checkk for the error if err == nil { //Print the yaml data fmt.Println(string(y_data)) }else{ fmt.Printf("Error while Marshaling. %v", err) } } The following output will appear after executing the script. Go to top Golang http request The net/http package of the Golang is used to send the http requests to a website. The http.Get() function is used to send the request. It returns the response from the site or the error message. The way of sending the http request to the website, https://example.com has been shown in the following script. package main //Import required packages import ( "fmt" "net/http" ) func main() { //Send a GET request to a website res, err := http.Get("https://example.com") //Check for error if err == nil { //Print the response sent by the website fmt.Println(res) }else{ //Print the error message fmt.Println(err) } } The following output will appear after executing the script. Go to top Golang command line arguments The values that are passed at the time of the execution of the script are called command-line argument values. The os package is used to read the command line argument values in Golang. The argument values are stored in the Args[] array. The for loop with the range has been used in the script to print the argument values without the script name in each line. package main //Imports required packages import ( "fmt" "os" ) func main() { fmt.Println("All argument values are:") //Print all argument values with the script name fmt.Println(os.Args) fmt.Println("Argument values:") //Print all argument values without a script name for in, _ := range os.Args { if in == 0 { continue } fmt.Println(os.Args[in]) } } The following output will appear after executing the script. Go to top Golang error handling Golang has no try-catch block like other programming languages. However, the errors package can be used in Golang to handle errors in the script. In the following script, an integer number will be taken from the user. If the user takes a negative number then an error message will be printed. The errors.New() function has been used here to generate the error message. package main //Import required packages import ( "errors" "fmt" ) func main() { var n int fmt.Printf("Enter a number: ") fmt.Scan(&n) //Check the input value result, err := Positive(n) //Check for error if err != nil { fmt.Println(err) } else { fmt.Printf("%d %s\n", n, result) } } ///Define function to check positive number func Positive(num int) (string, error) { if num < 0 { return "", errors.New("Type a positive number.") }else{ return "number is positive.", nil } } The following output will appear after executing the script. Go to top Conclusion: Golang is a popular programming language now that has many useful packages like the Python programming language. Any novice user can learn Golang as a first programming language because it is very easy to learn. The basic 30 Golang examples have been explained in this tutorial to learn Golang from the beginning and the learners will be able to write programs in Golang. One of the major limitations of this language is that it does not contain the features of object-oriented programming but it is good for learning structured programming. View the full article
  3. Golang (Go) is a programming language provided by Google to help developers create scalable and secure systems. Its simplicity makes any developer want to learn the language and use it quickly. While Go is a go-to programming language for many developers, you must first install it on Ubuntu 24.04 before you begin using it for your development. We’ve covered three installation methods that anyone can use. Read on! Three Methods of Installing Go on Ubuntu 24.04 The Go programming language has numerous applications, and as a Ubuntu user, you have three methods for installing Go. You can source it from the snap store or install it from the Ubuntu repository using APT. Still, you can download the Go tarball, extract it, and add its path to make it accessible on your system. All these methods are discussed below. Method 1: Install Go on Ubuntu 24.04 Via APT The first step in this method is to update the Ubuntu 24.04 repository. The Go version installed with this method is stable but not always the latest available version. Let’s first update the system. $ sudo apt update Next, use APT to install the Go package. $ sudo apt install golang-go Once the installation process is completed, view the installed Golang version. $ go version Method 2: Install Go Via Snap Even on Ubuntu 24.04 (Noble Numbat), you can access the Snap Store and install Snap packages. Go is available as a Snap package, and installing it via this approach will install even its dependencies. Here, you only need to execute the below command. $ sudo snap install go --classic Similarly, we can check the installed Go version. $ go version Notice how the two methods install the same Go version, which is the latest version when writing this post. Method 3: Install Go Via Its Official Repository The official way of installing Go on any Linux distribution is by sourcing its binary package. However, this is a long method as more steps are involved, but if you want the latest version or a specific Go version, this method is the best. The first step is to update the system. $ sudo apt update Next, visit the Go download page and find the version you want to install. Ensure you select the appropriate architecture for compatibility. We’ve chosen version 1.22.2 for this example. Once you’ve selected it, download the tarball using any utility. We’ve used wget for our example. $ wget https://go.dev/dl/go1.22.2.linux-amd64.tar.gz Allow the download to complete. The next step involves extracting the archive file. We’ve extracted it to the /usr/local/ directory using the tar command below. $ sudo tar -C /usr/local -xzf go1.20.1.linux-amd64.tar.gz $ ls /usr/local/go We’ve also run the ls command to confirm that the file was successfully unzipped and the new uncompressed Go folder containing all the required files exist. So far, we have the Go folder on our system, but we must add its binary to the path environment variable before we start using Go system-wide. Using a text editor, we will edit our bashrc to add the Go binary. Let’s open the file using the nano text editor. $ nano ~/.bashrc Next, paste the below line inside the file. export PATH=$PATH:/usr/local/go/bin Save the changes and exit the file. Also, source the file for the changes to apply. $ source ~/.bashrc Lastly, check the installed version. $ go version Test the Go Language Now that we’ve installed the Go programming language, we can use it for our development. Let’s create a simple ‘hello’ program to test that Go works correctly. Save it with a .go extension. Save the file and run it using the below syntax. $ go run program_name That’s it! The output confirms that Go is successfully installed on Ubuntu 24.04. Conclusion Go is a recent programming language developed by Google. Ubuntu supports Go and there are three ways you can install it. You can install it via APT or snap. Moreover, you can install it by downloading its official repository and adding its binary to your environment variable. Have fun using Go on Ubuntu 24.04. View the full article
  4. File operation is probably one of the most common operation when it comes to program, except for dealing with bugs. In Go, you will encounter such instances where you need to read a file line by line especially when dealing with text files. In this tutorial, we will walk you through all the methods and techniques on how we can read a file line by line. We start with the basic file reading techniques and progress to the more advanced features such as bufio and scanner libraries. We will also cover an example to help cement our understanding. Sample File Before we dive into the step of reading a file line by line, let us set up a basic file that we will use for demonstration purposes. In our case, we use a basic Terraform configuration as shown in the following output: # Define the AWS provider configuration provider "aws" { region = "us-east-1" } # Create a VPC resource "aws_vpc" "example_vpc" { cidr_block = "10.0.0.0/16" enable_dns_support = true enable_dns_hostnames = true } # Create two subnets in different availability zones resource "aws_subnet" "example_subnet1" { vpc_id = aws_vpc.example_vpc.id cidr_block = "10.0.1.0/24" availability_zone = "us-east-1a" map_public_ip_on_launch = true } resource "aws_subnet" "example_subnet2" { vpc_id = aws_vpc.example_vpc.id cidr_block = "10.0.2.0/24" availability_zone = "us-east-1b" map_public_ip_on_launch = true } # Create a security group for the EC2 instance resource "aws_security_group" "example_sg" { name = "example-sg" description = "Security group for EC2 instance" ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } # ---- more --------------------- The example file represents a Terraform configuration to set up an EC2 with a load balancer. Open the File in Golang Before we can read a file line by line, we need to open the file. Luckily, Go provides us with a simple and intuitive method of opening the files using the OS package. An example code is as follows: package main import ( "fmt" "os" ) func main() { fp := "./aws.tf" // Open the file for reading file, err := os.Open(fp) if err != nil { fmt.Println("Error:", err) return } defer file.Close() // File is now open and ready for reading } In the given example, we start by importing the packages that we require. In our case, we just need the fmt and OS packages. Next, we specify the path to the file that we want to open and save it to the “fp” variable. In our case, we want to open the “aws.tf” file. Finally, we use the os.Open() function to open the file and check any error that might occur when attempting to open the file. Read the File Line by Line in Golang Now that we have the target file open and ready to read, we can proceed and discuss the methods and techniques of reading the file line by line. Using the Bufio Package One of the most powerful packages in the Go ecosystem is the “bufio” package. This package implements the buffered I/O operations. It wraps the “io.Reader” and “io.Writer” object, creating another object that implements the interface but with buffer support. Method 1: Using Bufio.Scanner We can use the scanner type from this package to read a file line by line as demonstrated in the following example code: package main import ( "bufio" "fmt" "os" ) func main() { fp := "./aws.tf" file, err := os.Open(fp) if err != nil { fmt.Println("Error:", err) return } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Println("Error:", err) } } To use the scanner type, we start by creating a Scanner using the bufio.NewScanner(file) method where the file refers to the file that we opened for reading. We then use a “for” loop to iterate over the lines of the file using the scanner.Scan() method. Finally, we extract the text of each line using the scanner.Text() method and print it to the console. Method 2: Using Bufio.NewReader Another method that we can use is the NewReader() method from the “bufio” package. This allows us to read the lines of the file using the ReadString() function. An example is as follows: package main import ( "bufio" "fmt" "os" ) func main() { fp := "./aws.tf" file, err := os.Open(fp) if err != nil { fmt.Println("Error:", err) return } defer file.Close() reader := bufio.NewReader(file) for { line, err := reader.ReadString('\n') if err != nil { break } fmt.Print(line) } } In this approach, we create a “bufio.Reader” using the bufio.NewReader(file). We then use a “for” loop to read the lines using the reader.ReadString(‘\n’). The loop continues to read the file until an error occurs. For example, when we reach the end of the file. Using the Io Package Another package that comes in handy when dealing with I/O operations in Go is the “io” package. This package provides basic interfaces for I/O primitives. The primary task of the package is to wrap the existing implementations such as primitives from the OS package into shared public interfaces that abstract the functionality. Method 1: Using ReadString In the “io” package, we can use the ReadString() function to read a file line by line as shown in the following example: package main import ( "fmt" "io" "os" ) func main() { fp := "./aws.tf" file, err := os.Open(fp) if err != nil { fmt.Println("Error:", err) return } defer file.Close() buf := make([]byte, 1024) for { n, err := file.Read(buf) if err != nil { if err == io.EOF { break } fmt.Println("Error:", err) return } data := buf[:n] fmt.Print(string(data)) } } In this implementation, we start by opening a file for reading as we did in the previous examples. We then create a buffer called “buf” to read a chunk of data from the file. Lastly, we use a “for” loop with the file.Read() function to read the data into the buffer. We also check for “io.EOF” to determine when we reached the end of the file and terminate the loop. Method 2: Using ReadLine We also have access to the “ReadLine” function from the “io” package which can come in handy when we need to read a file line by line. An example is as follows: package main import ( "fmt" "io" "os" ) func splitLines(data []byte) [][]byte { var lines [][]byte for _, b := range data { if b == '\n' { lines = append(lines, []byte{}) } else { if len(lines) == 0 { lines = append(lines, []byte{}) } lines[len(lines)-1] = append(lines[len(lines)-1], b) } } return lines } func main() { fp := "./aws.tf" file, err := os.Open(fp) if err != nil { fmt.Println("Error:", err) return } defer file.Close() reader := io.Reader(file) buf := make([]byte, 1024) for { n, err := reader.Read(buf) if err != nil { if err == io.EOF { break } fmt.Println("Error:", err) return } data := buf[:n] lines := splitLines(data) for _, line := range lines { fmt.Println(string(line)) } } } In this case, we create a buffer and read the chunks of data from the file using the reader.Read() function. We then define a splitLines() function whose purpose is to split the data into lines by detecting when a new character is in the buff. Finally, we print the contents of the file. Conclusion In this tutorial, we learned a lot about file operations in Go. We learned how to use the “bufio” package, the Scanner type, and the NewReader. We also learned how to use the methods such as the “ReadString” and “ReadLine” functions to read a file line by line. View the full article
  5. A new low-level Go binding for the Terraform protocol for integrations to be built on top of; https://github.com/hashicorp/terraform-plugin-go
  6. Using the AWS Toolkit for VS Code, customers can now create, locally debug, and deploy Lambda functions written in Java and Go. Java users will be able to step-through debug Lambdas built with Maven and Gradle in Java 8, Java 8.al2, and Java 11, while Go users will be able to do the same with Lambdas built in Golang 1.14+. View the full article
  7. This article will focus on the popular monitoring tool Prometheus, and how to use PromQL. Prometheus uses Golang and allows simultaneous monitoring of many services and systems. View the full article
  8. Do you love Go? Do you maintain a project written in Go? Are you using Go in production? Are you a performance freak? If you answered “yes” to any of these questions, join our conference on all things Golang: cool libraries, frameworks and tools new paradigms, techniques and tricks adopting Golang for the first time in your team Golang and CI unorthodox ways of using Go anything else Go https://www.papercall.io/conf42-golang-2021
  9. until
    #GoVirCon ~ see you online! What Every Gopher Needs to Know! Call for Papers/Programming GopherCon's Call for Papers opened at the beginning of December and closed January 10th. We're excited to share that we received over 160 submissions! We're happy to announce our program has been officially decided and can be found on the Agenda page. We hope you are as pleased with this year's line-up as we are! The Call for Papers for 2021 will open December 1, 2020. We will post a link on Twitter. Pre-Conference Workshops A Pre-Conference Workshop Ticket is only valid on Monday, November 9th or Tuesday, November 10th, with the exception of the two-day pre-conference workshops that will be offered over the course of both days. The purchase of a Pre-Conference Workshop Ticket does not include access to the full conference, Wednesday, November 11th - Friday, November 13th, or vice versa. If you wish to attend the full conference, please purchase a Community Ticket or one of the two Promo Tickets listed below in addition to your Pre-Conference Workshop Ticket(s). Furthermore, based on the feedback of some of our experienced teachers, we have determined that 12:00 p.m. - 4:00 p.m. EST is the best time to offer a Pre-Conference workshop to ensure the largest "live" audience. However, if you are located in a "challenging" time zone or you would like to attend more than one workshop, we will be recording the presentations and emailing them to ticket holders. Which Ticket Should You Choose? If you have the means and you are able to support the conference, please consider the One-Time 20% Promo or One-Time 20% Promo, plus Perpetual 10% Promo outlined below. Otherwise, the Community Ticket is a separate purchase from any Pre-Conference Workshop Tickets. Scholarships GopherCon awards a limited number of Diversity Fund Scholarships each year to golang users in need. Though we are looking for diversity in both areas of gender and race, we absolutely consider need as well. The scholarship submission process opened at the beginning of December and closed January 8th. We are pleased to announce that we received over 170 applications this year and awarded 47 scholarships! All applicants have been notified of our decision. https://www.gophercon.com/
  • Forum Statistics

    43.9k
    Total Topics
    43.4k
    Total Posts
×
×
  • Create New...