julialangHow to use constructors in JuliaLang?
Constructors are used to create objects in JuliaLang. They are functions that take arguments and return an object.
Example
struct Point
x::Float64
y::Float64
end
function Point(x, y)
Point(x, y)
end
p = Point(1.0, 2.0)
Output example
Point(1.0, 2.0)
Code explanation
struct Point
: defines a new type calledPoint
x::Float64
andy::Float64
: define two fields of typeFloat64
function Point(x, y)
: defines a constructor function for thePoint
typePoint(x, y)
: creates a newPoint
object with the givenx
andy
valuesp = Point(1.0, 2.0)
: creates a newPoint
object withx
andy
values of1.0
and2.0
respectively
Helpful links
More of Julialang
- How to test code in JuliaLang?
- How to use assert in JuliaLang?
- How to measure execution time in JuliaLang?
- How to work with rational numbers in JuliaLang?
- How to work with matrices in JuliaLang?
- How to set up logging in JuliaLang?
- How to get JuliaLang version?
- How to use addprocs in JuliaLang?
- How to append to an array in JuliaLang?
- How to use try catch in JuliaLang?
See more codes...