Not Intuitive Type Declaration of Variable

123 views
Skip to first unread message

Diego Javier Zea

unread,
Dec 30, 2012, 8:02:06 AM12/30/12
to juli...@googlegroups.com
Suppose you want to be a to be the number 1 as a Uint8. In a computer of 64bits, you automatic get for a an Int64.

julia> a = 1
1
julia> typeof(a)
Int64

and If you want to use :: in order to obtain an Uint8, you only get type assertion

julia> a = 1::Uint8
type error: typeassert: expected Uint8, got Int64
julia> a::Uint8 = 1
a not defined

The only way I found is explicit convert to Uint8

julia> a = convert(Uint8,1)
0x01

Is there another way to do it?
Is there an analog for C's declaration of variables [ int a=1; ] ?


John Myles White

unread,
Dec 30, 2012, 8:20:48 AM12/30/12
to juli...@googlegroups.com
uint8(a)?

 -- John
--
 
 
 

Diego Javier Zea

unread,
Dec 30, 2012, 8:35:48 AM12/30/12
to juli...@googlegroups.com
A lot of Thanks, I complete forgot it!!!
But for some reason I expect to work the declaration a::Uint8 = 1
Maybe because in the Documentation says:

The “declaration” behavior only occurs in specific contexts:

x::Int8        # a variable by itself
local x::Int8  # in a local declaration
x::Int8 = 10   # as the left-hand side of an assignment

Why doesn't it work?

John Myles White

unread,
Dec 30, 2012, 8:41:24 AM12/30/12
to juli...@googlegroups.com
No idea. That's always seemed a little broken to me.

 -- John

--
 
 
 

Gabor

unread,
Dec 30, 2012, 9:07:21 AM12/30/12
to juli...@googlegroups.com
It already works in the local context.
 
> foo() = x::Uint8 = 10
 
> foo()
0x0a
 
> typeof(foo())
Uint8
 
It does not yet work in the global context (as the REPL).
But I have read somewhere that it is a planned feature.

Stefan Karpinski

unread,
Dec 31, 2012, 8:30:52 AM12/31/12
to Julia Dev
The recommended way to do this is uint8(1).


--
 
 
 

Gabor

unread,
Dec 31, 2012, 9:44:48 AM12/31/12
to juli...@googlegroups.com
Even in the local context?
If yes, the recommendation holds because of style or because of performance?

Stefan Karpinski

unread,
Dec 31, 2012, 10:03:42 AM12/31/12
to Julia Dev
In the local context, you can do either but they mean slightly different things. Writing uint8(1) gives you a Uint8 with an integer value of 1. Writing

x::Uint8 = 1

will also do that, but also if you assign a value to x later in the same scope, it will always be converted to Uint8. This can be useful sometimes when you want to ensure the type-stability of some iterative algorithm. Note that with either form conversion is done via convert(Uint8,1), so there's no performance difference.


--
 
 
 

Gabor

unread,
Dec 31, 2012, 10:06:56 AM12/31/12
to juli...@googlegroups.com
Thank you for the explanation!
Reply all
Reply to author
Forward
0 new messages