# How to initialize an empty vector of Float64

``````struct A{T}
time::Vector{Float64}
data::Vector{T}
end
``````

I would like to initialize an empty object of class A

I tried with outer constructor as below

``````A() = A([],[])
``````

But it failed:

`````` julia> a = A()
ERROR: MethodError: no method matching A(::Array{Any,1}, ::Array{Any,1})
Closest candidates are:
A(::Array{Float64,1}, ::Array{T,1}) where T at none:3
Stacktrace:
[1] A() at .\none:1
[2] top-level scope at none:0
``````

Thus, I tried to find out how to initialized

``````A() = A(Array{Float64}[],[])
``````

This is also failed

``````julia> a = A()
ERROR: MethodError: no method matching A(::Array{Array{Float64,N} where N,1}, ::Array{Any,1})
Closest candidates are:
A(::Array{Float64,1}, ::Array{T,1}) where T at none:3
Stacktrace:
[1] A() at .\none:1
[2] top-level scope at none:0

``````

How should we initialized an emtpy vector of Float64 type?

1 Like

You can do `A() = A(Float64[],[])`.

3 Likes

Perfect. Thank you!

1 Like

To expand on `@rfourquet`'s answer:

`[]` is a vector of `Any`, but your struct `A` requires a vector of `Float64`.

Moreover `Array{Float64}[]` is a vector of `Vector{Float64}` (you would have elements such as `[[1.0, 2.0], [3.0, 4.0, 5.0]]` for instance), which is why your third attempt fails.

`Float64[]` is also equivalent to `Vector{Float64}(undef, 0)`, which is a vector of `Float64` containing 0 elements of random (undef) content.

Note that `Vector{Float64}(undef, 0)` can be abridged to `Vector{Float64}()`. Also, to clarify for beginners, â€śrandom contentâ€ť here doesnâ€™t literally mean â€śrandomâ€ť but uninitialized (so content which might appear random, but is not initialized with random bits â€“ use `rand` for that).

4 Likes

The error in this case is mostly not because of a vector of `Float64` hasnâ€™t been passed, but because the compiler cannot infer type parameter from `A([], [])`.

If you write

``````A() = A{Any}([], [])
``````

then Julia happily converts the first `[]` to `Float64[]`.

That said, passing `Float64[]` as the first argument is better, as it avoids allocating a temporary `Any[]` just to throw it away.

2 Likes

Shouldnâ€™t it be like below, with the parameter T?

``````struct A{T}
time::Vector{Float64}
data::Vector{T}
end

A(T) = A(Float64[],T[])

julia>A(Int)
A{Int64}(Float64[], Int64[])
``````