How To Use Strings In Google Go

July 31st, 2010 by Kevin | 2 Comments | Filed in Go Programming

In the earlier tutorials, we have seen how to define variables and how to define constants in Google Go. This tutorial explains how we can use strings in Google Go programming.

Strings
The predeclared string type is string. Unlike C/C++ programming, Strings are length-delimited not NUL-terminated. Strings behave like arrays of bytes but are immutable: once created, it is impossible to change the contents of a string. In C++ terms, Go strings are a bit like const strings, while pointers to strings are analogous to const string references. Once you’ve built a string value, you can’t change it, although of course you can change a string variable simply by reassigning it.

This snippet from strings.go is legal code:

s := "hello"
if s[1] != 'e' { os.Exit(1) }
s = "good bye"
var p *string = &s
*p = "ciao"

However the following statements are illegal because they would modify a string value:

s[0] = 'x'
(*p)[1] = 'y'

The elements of strings have type byte and may be accessed using the usual indexing operations. It is illegal to take the address of such an element; if s[i] is theith byte of a string, &s[i] is invalid.

String literals
A string literal represents a string constant obtained from concatenating a sequence of characters. There are two forms: raw string literals and interpreted string literals.

Raw string literals are character sequences between back quotes ` `. Within the quotes, any character is legal except back quote. When using back quotes, backslashes have no special meaning and the string may span multiple lines.

Interpreted string literals are character sequences between double quotes ” “. The text between the quotes, which may not span multiple lines, forms the value of the literal, with backslash escapes interpreted as they are in character literals.

Below are some examples of both types of string literals. Google Go also supports Unicode strings.

`abc`  // same as "abc"
`\n
\n`    // same as "\\n\n\\n"
"\n"
""
"Hello, world!\n"
"日本語"                                 // UTF-8 input text
`日本語`                                 // UTF-8 input text as a raw literal

Strings can be concatenated using the ‘+’ operator. The length of string s can be discovered using the built-in function len(). The length is a compile-time constant if s is a string literal.

var string1 = "Hello World "
var string2 = "This is Google Go"
string3 := string1 + string2	//string3 = "Hello World This is Google Go"
len_string3 := len(string3)	//len_string3 = 29

Google Go provides a “strings” package that consists of several functions to manipulate strings. You can find more information at http://golang.org/pkg/strings/.

 

Related Posts:

Tags:

How To Define Constants in Google Go

July 29th, 2010 by Kevin | No Comments | Filed in Go Programming

In the previous tutorial, we saw how to define variables in Google Go. In today’s tutorial, we check out how we can declare constants and enumerated constants in Google Go.

Constants
The types of constants available in Go programming are boolean constants, integer constants, floating-point constants, complex constants, and string constants. Constants in Go are created at compile time, even when defined as locals in functions.

Constants are declared similar to variables except that the const keyword is used. Also we cannot use the idiom (using :=) as done for variable declaration.

Below are examples of declaring different types of constants in Go programming.

const Pi float64 = 3.14159265358979323846   //typed floating-point constant
const zero = 0.0             // untyped floating-point constant
const (
        size int64 = 1024   //typed integer constant
        eof = -1             // untyped integer constant
)
const a, b, c = 3, 4, "foo"  // a = 3, b = 4, c = "foo", untyped integer and string constants
const u, v float = 0, 3      // u = 0.0, v = 3.0
const sum = 1 – 0.707i   ///complex constant
const flag bool = true

Enumerated Constants
In Go, enumerated constants are created using the iota enumerator. This can be considered similar to enumeration in C. It is reset to 0 whenever the reserved word const appears in the source and increments after each use of iota as shown below.

const (  // iota is reset to 0
        c0 = iota  // c0 == 0
        c1 = iota  // c1 == 1
        c2 = iota  // c2 == 2
)

const (
        a = 1 << iota  // a == 1 (iota has been reset)
        b = 1 << iota  // b == 2
        c = 1 << iota  // c == 4
)

const (
        u       = iota * 42  // u == 0     (untyped integer constant)
        v float = iota * 42  // v == 42.0  (float constant)
        w       = iota * 42  // w == 84    (untyped integer constant)
)

const x = iota  // x == 0 (iota has been reset)
const y = iota  // y == 0 (iota has been reset)
 

Related Posts:

Tags:

How To Define Variables In Google Go

July 28th, 2010 by Kevin | No Comments | Filed in Go Programming

In the previous tutorial, we began by writing a Hello World program in Google Go. This tutorial will look into the available primitive data types and how to declare and define variables in Go programming.

Basic Data Types
The following are the basic data types that are available in the Google Go programming language.

bool          boolean truth values of either true or false
uint8         the set of all unsigned  8-bit integers (0 to 255)
uint16       the set of all unsigned 16-bit integers (0 to 65535)
uint32       the set of all unsigned 32-bit integers (0 to 4294967295)
uint64       the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8          the set of all signed  8-bit integers (-128 to 127)
int16        the set of all signed 16-bit integers (-32768 to 32767)
int32        the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64        the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers

complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts

byte        familiar alias for uint8

uint         either 32 or 64 bits
int          either 32 or 64 bits
float       either 32 or 64 bits

string      represents the set of string values

To avoid portability issues all numeric types are distinct except byte, which is an alias for uint8. Conversions are required when different numeric types are mixed in an expression or assignment. For instance, int32 and int are not the same type even though they may have the same size on a particular architecture.

Variables

A computer variable can represent any kind of data that can be stored in a computer system.
Variables in the Go programming language can be declared as,

    var s string = ""

This is the var keyword, followed by the name of the variable, followed by its type, followed by an equals sign and an initial value for the variable.
Go tries to be terse, and this declaration could be shortened. Since the string constant is of type string, we don’t have to tell the compiler that. We could write

    var s = ""

or we could go even shorter and write the idiom

    s := ""

Following are several example of declaring different types of variables in Go.

var i int
var U, V, W float
var k = 0
var x, y float = -1, -2
var (
        i int
        u, v, s = 2.0, 3.0, "bar"
)

If no initial value is given to a variable, then that variable is initialized to it’s zero value. False for booleans, 0 for integers, 0.0 for floats, “” for strings, and nil for pointers, functions, interfaces, slices, channels, and maps.

Type Conversions
Go does not support implicit type conversion. To convert a numeric value from one type to another is a conversion, with syntax like a function call:

  uint8(int_var)     // truncate to size
  int(float_var)     // truncate fraction
  float64(int_var) // convert to float

Also some conversions to string:

  string(0x1234)            // == "\u1234"
  string(array_of_bytes)    // bytes -> bytes
  string(array_of_ints)     // ints -> Unicode/UTF-8
 

Related Posts:

Tags: