Julia 是一种动态类型语言,即变量的类型不需要在程序中静态声明。除此之外,它还提供了一种在运行时向 Just-in-Time (JIT) 编译器评论变量类型的技术。此外,Julia 支持动态和静态类型。 Julia 的这一独特特性使其与其他编程语言不同。
类型注释
Julia 中的类型注释变量可以使用::运算符。此运算符确认左侧的值与右侧的值的类型相同。
Syntax:
where,
expr: It can be an expression for computing a value or an assignment statement for a variable or an declaration of a variable.
type: It is the data type of the variable being used in the program.
Julia 类型注释可用于两种类型的表达式:
类型断言:它是一个表达式,用于计算变量的某个值。
示例 1:
Julia
# Julia program to illustrate Type Assertion
b = 10
# assures at runtime that 'b' will be an integer
a = b :: Int
print(a)
Julia
# Julia program to illustrate Type Assertion
c = 20.5
d = 30.4
# assures at runtime that 'c+d' will be a float64
c + d::Float64
print(c + d)
Julia
# Julia program to illustrate Type Assertion
c = 10.5
# assures at runtime that 'c+c' will be an integer
c + c::Int
Julia
# Julia program for variable type declaration
struct example
# this field will always contain only integer values
x ::Int
end
x = 20
print(x)
Julia
# Julia program for variable type declaration
struct Person
# this field will always contain only string values
name::String
# this field will always contain only integer values
age::Int
end
p = Person("Max", 24)
Julia
# Function accepting Float64 value
# and returning a Float32 value
function example(x ::Float64) ::Float32
cos(π * x)
end
# calling the function
result = example(1.5)
# print result
print(result)
输出:
示例 2:
朱莉娅
# Julia program to illustrate Type Assertion
c = 20.5
d = 30.4
# assures at runtime that 'c+d' will be a float64
c + d::Float64
print(c + d)
输出:
示例 3:
朱莉娅
# Julia program to illustrate Type Assertion
c = 10.5
# assures at runtime that 'c+c' will be an integer
c + c::Int
输出:
ERROR: TypeError: in typeassert, expected Int64, got a value of type Float64
Stacktrace:
[1] top-level scope at REPL[2]:1
变量类型声明:
- 这些是局部变量的赋值或声明的左侧。
- 它还涵盖了结构和命名元组的类型字段。
- 函数参数和返回类型也可以进行类型注释。
示例 4:
朱莉娅
# Julia program for variable type declaration
struct example
# this field will always contain only integer values
x ::Int
end
x = 20
print(x)
输出:
示例 5:
朱莉娅
# Julia program for variable type declaration
struct Person
# this field will always contain only string values
name::String
# this field will always contain only integer values
age::Int
end
p = Person("Max", 24)
输出:
示例 6:
朱莉娅
# Function accepting Float64 value
# and returning a Float32 value
function example(x ::Float64) ::Float32
cos(π * x)
end
# calling the function
result = example(1.5)
# print result
print(result)
输出: