Shubham Ankit

Shubham Ankit

1563426074

Golang Constants Tutorial With Example | Constants In Go

Golang Constants Tutorial With Example | Constants in Go is today’s topic. Go supports the constants of character, string, boolean, and numeric values

Constants are created at compile time, even when defined as locals in functions, and can only number, characters (runes), strings or booleans. Because of Golang’s compile-time restriction, the expressions that define them must be constant expressions which is evaluated by the compiler.

Content Overview

  • 1 Golang Constants Tutorial
  • 2 Declaring a Constant in Golang
  • 3 Typed and Untyped Constants
  • 4 Untyped Constants in Golang
  • 5 Typed Constants in Golang

Golang Constants Tutorial

The const declares a constant value. Constant expressions perform arithmetic with arbitrary precision. The numeric constant has no type until it’s given, such as by an explicit cast.

A number can be given the type by using it in a context that requires one, such as the variable assignment or a function call.

In Golang, we use a term constant represent fixed (unchanging) values such as 3.14, 21, “Hello,” etc.

Literals are constants. All the literals in Go, be it integer literals like 21, 46, or floating-point literals like 3.14, 19.21, or boolean literals like true, false, or string literals like “Krunal,”Ankit” areconstants.

Declaring a Constant in Golang

We can declare a constant and give it a name, and you can use the keyword **const **like the following.

const blog = "AppDividend"
const flag = true

You can also specify the type in the declaration like the following code.

const x int = 1921
const y string = "Krunal"

We can also define multiple constants. See the following code.

// hello.go

package main

import "fmt"

func main() {
    const name, country = "Krunal", "India"

    const (
        stockName  string  = "Infosys"
        stockPrice float64 = 702.50
    )
    fmt.Println(stockName, stockPrice)
        fmt.Println(name, country)
}

See the below output.

Now, let’s try to modify the value of the constants and see the result.

// hello.go

package main

import "fmt"

func main() {
    const name, country = "Krunal", "India"
    name = "Ankit"
    fmt.Println(name, country)
}

See the below output.

So, we have got the error like Cannot assign the constant.

Typed and Untyped Constants

Go is the statically typed programming language. Which means that a type of every variable is known or inferred by the compiler at the compile time. But it goes beyond that step with its type system and doesn’t even allow us to perform the operations that mix numeric types. For example, We cannot add the float64 variable to an int, or yet an int64 variable to an int. See the following code.

// hello.go

package main

func main() {
    var floatVal float64 = 3.14
    var intVal int = 19
    var int64Val int64 = 21

    var o1 = floatVal + intVal
    var o2 = intVal + int64Val
}

See the below output.

So, we have got the error like invalid operation. Golang doesn’t provide an implicit type conversion, and it requires you to do the explicit type casting whenever we mix the variables of multiple types in the operation.

Untyped Constants in Golang

Any constant in Go, named or unnamed, is an untyped unless given a type explicitly. See the following examples.

21       // untyped integer constant
1.9     // untyped floating-point constant
false    // untyped boolean constant
"Cloud"

See the untyped constants even after you give the name.

const x = 19
const y = 2.1
const z = false
const w = "Zing"

Let’s now see the example of an untyped string constant.

In Go, you can create the type alias using the type keyword like the following.

type AppDividend string

Given the strongly typed nature of the Golang, you can’t assign the string variable to an AppDividend variable.

// hello.go

package main

func main() {
    type AppDividend string
    var mString string = "Hello"
    var mStringA AppDividend = mString
}

See the below output.

Untyped constants are a fantastic design decision taken by Go creators. Although Go has a robust type system, You can use the untyped constants to escape from the Go’s type system and have more flexibility when working with a mixed data types in any expression.

Typed Constants in Golang

In Go, Constants are typed when you explicitly specify a type in the declaration like the following syntax.

const typedInt int = 21

Just like the variables, all the rules of Go’s type system applies to the typed constant. For example, you cannot assign the typed integer constant to a float variable. See the following code.

var myFloat64 float64 = typedInt  // Compiler Error

With the typed constants, you lose all the flexibility that comes with the untyped constants like assigning them to any variable of the compatible type or mixing them in the mathematical operations. So you should declare the type for a constant only if it’s necessary. Otherwise, declare constants without a type.

#go #web-development

What is GEEK

Buddha Community

Golang Constants Tutorial With Example | Constants In Go
Fannie  Zemlak

Fannie Zemlak

1599854400

What's new in the go 1.15

Go announced Go 1.15 version on 11 Aug 2020. Highlighted updates and features include Substantial improvements to the Go linker, Improved allocation for small objects at high core counts, X.509 CommonName deprecation, GOPROXY supports skipping proxies that return errors, New embedded tzdata package, Several Core Library improvements and more.

As Go promise for maintaining backward compatibility. After upgrading to the latest Go 1.15 version, almost all existing Golang applications or programs continue to compile and run as older Golang version.

#go #golang #go 1.15 #go features #go improvement #go package #go new features

Arvel  Miller

Arvel Miller

1603439853

The Nuances of Constants in Go; Go Isn't JavaScript

Constants can be confusing and easy to misuse in Go if you are coming from an untyped language. Let’s take a look at some of the nuanced details of how they work in Go. It’s probably unsurprising, but Go’s constants are almost nothing like JavaScript’s bastardized version of the concept.

Go vs JavaScript

Many programming languages support constants, often denoted by the keyword const.

Go and JavaScript both declare new constants in the same way:

const frameRate = 60

Constants in Go

  • Must be able to be assigned at compile time. The value of a const can’t be the result of a runtime calculation.
  • Run faster because the compiler can make specific optimizations.
  • Cannot change. The compiler will not allow them to be re-assigned.
  • Only work with some types. Arrays, Slices, Maps, Structs, etc… can’t be made constant
  • Are not normal Go types unless explicitly assigned as such

#languages #clean code #engineering practices #golang #javascript #compile #const #constant #global #go #golang #javascript

Neal  Bode

Neal Bode

1599287850

Golang Array Example | Arrays in Go Tutorial Explained

Golang array is a fixed-size collection of items of the same type. The items of an array are stored sequentially and can be accessed using their index. If we want to declare an array in Go, a programmer specifies the type of the elements and the number of items required by an array.

Golang array example

Golang programming language provides a data structure called an** array**, which can store the fixed-size sequential collection of items of the same type.

The array is used to store the collection of data, but it is often more useful to think of the array as the collection of variables of the same type.

Instead of declaring individual variables, such as no1, no2, …, and no99, you declare one array variable such as numbers and use no[0], no[1], and …, no[99] to represent individual variables.

#golang #go #golang array #golang programming

张 小龙

1596440100

Anatomy of Conditional Statements and Loops in Go

Go provides if/else and switch conditional statements for code execution based on certain conditions. To execute some code over and over again, we have the for loop.

The if/else conditional statement

Go provides if, if-else, if-else if-else variants of if/else statement we are familiar with. It is used to check a condition, and execute some code when the condition is true or false.

The if condition

Simple use of if condition is demonstrated below. Unlike most of the programming languages, Go does not allow to wrap the condition inside parenthesis ().

#golang #programming #golang-tutorial #go-tutorial #go

Zander  Herzog

Zander Herzog

1596793260

Secure HTTPS servers in Go

In this article, we are going to look at some of the basic APIs of the http package to create and initialize HTTPS servers in Go.

Image for post

(source: unsplash.com)

In the “Simple Hello World Server” lesson, we learned about net/http package, how to create routes and how [ServeMux](https://golang.org/pkg/net/http/#ServeMux) works. In the “Running multiple HTTP servers” lesson, we learned about [Server](https://golang.org/pkg/net/http/#Server) structure and how to run multiple HTTP servers concurrently.

In this lesson, we are going to create an HTTPS server using both Go’s standard server configuration and custom configuration (using [_Server_](https://golang.org/pkg/net/http/#Server) structure). But before this, we need to know what HTTPS really is?

HTTPS is a big topic of discussion in itself. Hence while writing this lesson, I published an article just on “How HTTPS works?”. I advise you to read this lesson first before continuing this article. In this article, I’ve also described the encryption paradigm and SSL certificates generation process.


If we recall the simplest HTTP server example from previous lessons, we only need http.``[ListenAndServe](https://golang.org/pkg/net/http/#ListenAndServe) function to start an HTTP server and http.``[HandleFunc](https://golang.org/pkg/net/http/#HandleFunc) to register a response handler for a particular endpoint.

Image for post

(https://play.golang.org/p/t3sOenOYAzS)

In the example above, when we run the command go run server.go , it will start an HTTP server on port 9000. By visiting http://localhost:9000 URL in a browser, you will be able to see a Hello World! message on the screen.

Image for post

(http://localhost:9000)

As we know, the nil argument to ListenAndServe() call invokes Go to use the [DefaultServeMux](https://golang.org/pkg/net/http/#DefaultServeMux) response multiplexer, which is the default instance of ServeMux structure provided globally by the Go. The HandleFunc() call adds a response handler for a specific route on the multiplexer instance.

The http.ListenAndServe() call uses the Go’s standard HTTP server configuration, however, in the previous lesson, how we can customize a server using [Server](https://golang.org/pkg/net/http/#Server) structure type.

To start an HTTPS server, all we need do is to call ServerAndListenTLS method with some configuration. Just like ServeAndListen method, this method is available on both the http package and the Server structure.

The http.``[ServeAndListenTLS](https://golang.org/pkg/net/http/#ListenAndServeTLS) method uses the Go’s standard server implementation, however, both [Server](https://golang.org/pkg/net/http/#Server) instance and Server.``[ServeAndListenTLS](https://golang.org/pkg/net/http/#Server.ListenAndServeTLS) method can be configured for our needs.

#go-programming-language #go #golang-tutorial #go-programming #golang