Go Integers: Difference between revisions
Line 18: | Line 18: | ||
var i int // string type declaration without initialization | var i int // string type declaration without initialization | ||
i = 1 // initialization after declaration | i = 1 // initialization after declaration | ||
var i2 int = 2 | var i2 int = 2 // variable initialization in declaration | ||
var i3 = 3 // variable initialization with type inference | var i3 = 3 // variable initialization with type inference | ||
i4 := 4 // short variable declaration | i4 := 4 // short variable declaration |
Revision as of 02:01, 20 August 2023
Internal
Overview
Integers are designated by the following pre-declared type identifiers.
In most cases, we simply declare an int
(signed integer) or uint
(unsigned integer) and leave it to the compiler to allocate the right type of integer, depending on the underlying architecture. If we want to get specific, we can use:
- Unsigned integers represented on the specified number of bits:
uint8
(byte
),uint16
,uint32
(rune
, also see strings),uint64
. - Signed integers, represented on the specified number of bits:
int8
,int16
,int32
,int64
. Internally they are stored in 2's complement representation. - Machine-dependent integers:
uint
,int
anduintptr
.int
, for example, can be 4 bytes or 8 bytes long, depending on the underlying architecture.
When a regular integer is needed in the program, int
should be the default.
The uninitialized value is 0
.
Integer Variable Declaration
var i int // string type declaration without initialization
i = 1 // initialization after declaration
var i2 int = 2 // variable initialization in declaration
var i3 = 3 // variable initialization with type inference
i4 := 4 // short variable declaration
Integer Literals
Operators
Binary Operators
Arithmetic: +
, -
, *
, /
, %
, <<
, >>
Comparison: ==
, !=
, >
, <
, >=
, <=
Boolean: &&
, ||
byte
byte
is unsigned int represented on a byte (uint8
).
Indexing operator [] applied to strings return bytes.
Conversion between bytes and strings
A single byte can be converted to string as follows:
var b byte = 65 // decimal ASCII for "A"
str := string(b) // str is "A"
The following expression converts a string to a slice of bytes:
bytes := []byte("test")
The following expression converts a slice of bytes to string:
str := string(bytes)
Also see:
Integers as characters
i := 'A'
j := i + 1
fmt.Printf("%c %d\n", j, j)
Also see:
Integers to Strings
i := 0
string(48 + i)