Reputation: 11687
I have such code:
type ErrNegativeSqrt float64
Why such construct is available?
float64(ErrNegativeSqrt(-2))
Which 'mechanics' is used to store -2 in ErrNegativeSqrt
?
Upvotes: 2
Views: 254
Reputation: 7850
This is called conversions, see here: http://golang.org/ref/spec#Conversions . It describes how a value can be created by converting another value into that type when it i compatible. And here the -2 can be represented as float64.
Upvotes: 1
Reputation: 166549
ErrNegativeSqrt
is a type
not a variable. Values are stored in variables.
type ErrNegativeSqrt float64
// x is a variable of type ErrNegativeSqrt with an initial value of -2
var x ErrNegativeSqrt = -2
UPDATE:
The Go Programming Language Specification
There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Character, integer, floating-point, and complex constants are collectively called numeric constants.
A constant value is represented by a rune, integer, floating-point, imaginary, or string literal, an identifier denoting a constant, a constant expression, a conversion with a result that is a constant, or the result value of some built-in functions such as unsafe.Sizeof applied to any value, cap or len applied to some expressions, real and imag applied to a complex constant and complex applied to numeric constants. The boolean truth values are represented by the predeclared constants true and false. The predeclared identifier iota denotes an integer constant.
Numeric constants represent values of arbitrary precision and do not overflow.
Constants may be typed or untyped. Literal constants, true, false, iota, and certain constant expressions containing only untyped constant operands are untyped.
A constant may be given a type explicitly by a constant declaration or conversion, or implicitly when used in a variable declaration or an assignment or as an operand in an expression.
Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.
ErrNegativeSqrt(-2)
is a conversion. The untyped constant -2
is converted to type ErrNegativeSqrt
because, as an operand, it can be represented in ErrNegativeSqrt
's float64
underlying type.
Upvotes: 4
Reputation: 33432
ErrNegativeSqrt(-2) is possible because ErrNegativeSqrt is a float64 internally, which is described by the spec as able to hold "IEEE-754 64-bit floating-point numbers".
http://en.wikipedia.org/wiki/IEEE_floating_point
Upvotes: 1