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 round numbers in JuliaLang?
- How to get JuliaLang version?
- How to use tuples in JuliaLang?
- How to use the JuliaLang package manager?
- How to install JuliaLang?
- How to solve differential equations in JuliaLang?
- How to use try catch in JuliaLang?
- How to use regular expressions in JuliaLang?
- How to calculate the mean in JuliaLang?
See more codes...