基本功能
介绍
Julia Base 中包含一系列适用于科学及数值计算的函数和宏,但也可以用于通用编程,其它功能则由 Julia 生态圈中的各种库来提供。函数按主题划分如下:
一些通用的提示:
- 可以通过
Import Module导入想要使用的模块,并利用Module.fn(x)语句来实现对模块内函数的调用。 - 此外,
using Module语句会将名为Module的模块中的所有可调函数引入当前的命名空间。 - 按照约定,名字以感叹号(
!)结尾的函数会改变其输入参数的内容。 一些函数同时拥有改变参数(例如sort!)和不改变参数(sort)的版本
概览
Base.exit — Function
1. exit(code=0)
Stop the program with an exit code. The default exit code is zero, indicating that the program completed successfully. In an interactive session, exit() can be called with the keyboard shortcut ^D.
Base.atexit — Function
1. atexit(f)
Register a zero-argument function f() to be called at process exit. atexit() hooks are called in last in first out (LIFO) order and run before object finalizers.
Base.isinteractive — Function
1. isinteractive() -> Bool
Determine whether Julia is running an interactive session.
Base.summarysize — Function
1. Base.summarysize(obj; exclude=Union{...}, chargeall=Union{...}) -> Int
Compute the amount of memory, in bytes, used by all unique objects reachable from the argument.
Keyword Arguments
exclude: specifies the types of objects to exclude from the traversal.chargeall: specifies the types of objects to always charge the size of all of their fields, even if those fields would normally be excluded.
Base.require — Function
1. require(into::Module, module::Symbol)
This function is part of the implementation of using / import, if a module is not already defined in Main. It can also be called directly to force reloading a module, regardless of whether it has been loaded before (for example, when interactively developing libraries).
Loads a source file, in the context of the Main module, on every active node, searching standard locations for files. require is considered a top-level operation, so it sets the current include path but does not use it to search for files (see help for include). This function is typically used to load library code, and is implicitly called by using to load packages.
When searching for files, require first looks for package code in the global array LOAD_PATH. require is case-sensitive on all platforms, including those with case-insensitive filesystems like macOS and Windows.
For more details regarding code loading, see the manual sections on modules and parallel computing.
Base.compilecache — Function
1. Base.compilecache(module::PkgId)
Creates a precompiled cache file for a module and all of its dependencies. This can be used to reduce package load times. Cache files are stored in DEPOT_PATH[1]/compiled. See Module initialization and precompilation for important notes.
Base.__precompile__ — Function
1. __precompile__(isprecompilable::Bool)
Specify whether the file calling this function is precompilable, defaulting to true. If a module or file is not safely precompilable, it should call __precompile__(false) in order to throw an error if Julia attempts to precompile it.
Base.include — Function
1. Base.include([m::Module,] path::AbstractString)
Evaluate the contents of the input source file in the global scope of module m. Every module (except those defined with baremodule) has its own 1-argument definition of include, which evaluates the file in that module. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls to include will search relative to that path. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.
Base.MainInclude.include — Function
1. include(path::AbstractString)
Evaluate the contents of the input source file in the global scope of the containing module. Every module (except those defined with baremodule) has its own 1-argument definition of include, which evaluates the file in that module. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls to include will search relative to that path. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.
Use Base.include to evaluate a file into another module.
Base.include_string — Function
1. include_string(m::Module, code::AbstractString, filename::AbstractString="string")
Like include, except reads code from the given string rather than from a file.
Base.include_dependency — Function
1. include_dependency(path::AbstractString)
In a module, declare that the file specified by path (relative or absolute) is a dependency for precompilation; that is, the module will need to be recompiled if this file changes.
This is only needed if your module depends on a file that is not used via include. It has no effect outside of compilation.
Base.which — Method
1. which(f, types)
Returns the method of f (a Method object) that would be called for arguments of the given types.
If types is an abstract type, then the method that would be called by invoke is returned.
Base.methods — Function
1. methods(f, [types])
Returns the method table for f.
If types is specified, returns an array of methods whose types match.
Base.@show — Macro
1. @show
Show an expression and result, returning the result. See also show.
ans — Keyword
1. ans
A variable referring to the last computed value, automatically set at the interactive prompt.
关键字
module — Keyword
1. module
module declares a Module, which is a separate global variable workspace. Within a module, you can control which names from other modules are visible (via importing), and specify which of your names are intended to be public (via exporting). Modules allow you to create top-level definitions without worrying about name conflicts when your code is used together with somebody else’s. See the manual section about modules for more details.
Examples
1. module Foo
2. import Base.show
3. export MyType, foo
5. struct MyType
6. x
7. end
9. bar(x) = 2x
10. foo(a::MyType) = bar(a.x) + 1
11. show(io::IO, a::MyType) = print(io, "MyType $(a.x)")
12. end
export — Keyword
1. export
export is used within modules to tell Julia which functions should be made available to the user. For example: export foo makes the name foo available when using the module. See the manual section about modules for details.
import — Keyword
1. import
import Foo will load the module or package Foo. Names from the imported Foo module can be accessed with dot syntax (e.g. Foo.foo to access the name foo). See the manual section about modules for details.
using — Keyword
1. using
using Foo will load the module or package Foo and make its exported names available for direct use. Names can also be used via dot syntax (e.g. Foo.foo to access the name foo), whether they are exported or not. See the manual section about modules for details.
baremodule — Keyword
1. baremodule
baremodule declares a module that does not contain using Base or a definition of eval. It does still import Core.
function — Keyword
1. function
Functions are defined with the function keyword:
1. function add(a, b)
2. return a + b
3. end
Or the short form notation:
1. add(a, b) = a + b
The use of the return keyword is exactly the same as in other languages, but is often optional. A function without an explicit return statement will return the last expression in the function body.
macro — Keyword
1. macro
macro defines a method for inserting generated code into a program. A macro maps a sequence of argument expressions to a returned expression, and the resulting expression is substituted directly into the program at the point where the macro is invoked. Macros are a way to run generated code without calling eval, since the generated code instead simply becomes part of the surrounding program. Macro arguments may include expressions, literal values, and symbols.
Examples
1. julia> macro sayhello(name)
2. return :( println("Hello, ", $name, "!") )
3. end
4. @sayhello (macro with 1 method)
6. julia> @sayhello "Charlie"
7. Hello, Charlie!
return — Keyword
1. return
return x causes the enclosing function to exit early, passing the given value x back to its caller. return by itself with no value is equivalent to return nothing (see nothing).
1. function compare(a, b)
2. a == b && return "equal to"
3. a < b ? "less than" : "greater than"
4. end
In general you can place a return statement anywhere within a function body, including within deeply nested loops or conditionals, but be careful with do blocks. For example:
1. function test1(xs)
2. for x in xs
3. iseven(x) && return 2x
4. end
5. end
7. function test2(xs)
8. map(xs) do x
9. iseven(x) && return 2x
10. x
11. end
12. end
In the first example, the return breaks out of test1 as soon as it hits an even number, so test1([5,6,7]) returns 12.
You might expect the second example to behave the same way, but in fact the return there only breaks out of the inner function (inside the do block) and gives a value back to map. test2([5,6,7]) then returns [5,12,7].
When used in a top-level expression (i.e. outside any function), return causes the entire current top-level expression to terminate early.
do — Keyword
1. do
Create an anonymous function and pass it as the first argument to a function call. For example:
1. map(1:10) do x
2. 2x
3. end
is equivalent to map(x->2x, 1:10).
Use multiple arguments like so:
1. map(1:10, 11:20) do x, y
2. x + y
3. end
begin — Keyword
1. begin
begin...end denotes a block of code.
1. begin
2. println("Hello, ")
3. println("World!")
4. end
Usually begin will not be necessary, since keywords such as function and let implicitly begin blocks of code. See also ;.
end — Keyword
1. end
end marks the conclusion of a block of expressions, for example module, struct, mutable struct, begin, let, for etc. end may also be used when indexing into an array to represent the last index of a dimension.
Examples
1. julia> A = [1 2; 3 4]
2. 2×2 Array{Int64,2}:
3. 1 2
4. 3 4
6. julia> A[end, :]
7. 2-element Array{Int64,1}:
8. 3
9. 4
let — Keyword
1. let
let statements allocate new variable bindings each time they run. Whereas an assignment modifies an existing value location, let creates new locations. This difference is only detectable in the case of variables that outlive their scope via closures. The let syntax accepts a comma-separated series of assignments and variable names:
1. let var1 = value1, var2, var3 = value3
2. code
3. end
The assignments are evaluated in order, with each right-hand side evaluated in the scope before the new variable on the left-hand side has been introduced. Therefore it makes sense to write something like let x = x, since the two x variables are distinct and have separate storage.
if — Keyword
1. if/elseif/else
if/elseif/else performs conditional evaluation, which allows portions of code to be evaluated or not evaluated depending on the value of a boolean expression. Here is the anatomy of the if/elseif/else conditional syntax:
1. if x < y
2. println("x is less than y")
3. elseif x > y
4. println("x is greater than y")
5. else
6. println("x is equal to y")
7. end
If the condition expression x < y is true, then the corresponding block is evaluated; otherwise the condition expression x > y is evaluated, and if it is true, the corresponding block is evaluated; if neither expression is true, the else block is evaluated. The elseif and else blocks are optional, and as many elseif blocks as desired can be used.
for — Keyword
1. for
for loops repeatedly evaluate a block of statements while iterating over a sequence of values.
Examples
1. julia> for i in [1, 4, 0]
2. println(i)
3. end
4. 1
5. 4
6. 0
while — Keyword
1. while
while loops repeatedly evaluate a conditional expression, and continue evaluating the body of the while loop as long as the expression remains true. If the condition expression is false when the while loop is first reached, the body is never evaluated.
Examples
1. julia> i = 1
2. 1
4. julia> while i < 5
5. println(i)
6. global i += 1
7. end
8. 1
9. 2
10. 3
11. 4
break — Keyword
1. break
Break out of a loop immediately.
Examples
1. julia> i = 0
2. 0
4. julia> while true
5. global i += 1
6. i > 5 && break
7. println(i)
8. end
9. 1
10. 2
11. 3
12. 4
13. 5
continue — Keyword
1. continue
Skip the rest of the current loop iteration.
Examples
1. julia> for i = 1:6
2. iseven(i) && continue
3. println(i)
4. end
5. 1
6. 3
7. 5
try — Keyword
1. try/catch
A try/catch statement allows intercepting errors (exceptions) thrown by throw so that program execution can continue. For example, the following code attempts to write a file, but warns the user and proceeds instead of terminating execution if the file cannot be written:
1. try
2. open("/danger", "w") do f
3. println(f, "Hello")
4. end
5. catch
6. @warn "Could not write file."
7. end
or, when the file cannot be read into a variable:
1. lines = try
2. open("/danger", "r") do f
3. readlines(f)
4. end
5. catch
6. @warn "File not found."
7. end
The syntax catch e (where e is any variable) assigns the thrown exception object to the given variable within the catch block.
The power of the try/catch construct lies in the ability to unwind a deeply nested computation immediately to a much higher level in the stack of calling functions.
finally — Keyword
1. finally
Run some code when a given block of code exits, regardless of how it exits. For example, here is how we can guarantee that an opened file is closed:
1. f = open("file")
2. try
3. operate_on_file(f)
4. finally
5. close(f)
6. end
When control leaves the try block (for example, due to a return, or just finishing normally), close(f) will be executed. If the try block exits due to an exception, the exception will continue propagating. A catch block may be combined with try and finally as well. In this case the finally block will run after catch has handled the error.
quote — Keyword
1. quote
quote creates multiple expression objects in a block without using the explicit Expr constructor. For example:
1. ex = quote
2. x = 1
3. y = 2
4. x + y
5. end
Unlike the other means of quoting, :( ... ), this form introduces QuoteNode elements to the expression tree, which must be considered when directly manipulating the tree. For other purposes, :( ... ) and quote .. end blocks are treated identically.
local — Keyword
1. local
local introduces a new local variable. See the manual section on variable scoping for more information.
Examples
1. julia> function foo(n)
2. x = 0
3. for i = 1:n
4. local x # introduce a loop-local x
5. x = i
6. end
7. x
8. end
9. foo (generic function with 1 method)
11. julia> foo(10)
12. 0
global — Keyword
1. global
global x makes x in the current scope and its inner scopes refer to the global variable of that name. See the manual section on variable scoping for more information.
Examples
1. julia> z = 3
2. 3
4. julia> function foo()
5. global z = 6 # use the z variable defined outside foo
6. end
7. foo (generic function with 1 method)
9. julia> foo()
10. 6
12. julia> z
13. 6
const — Keyword
1. const
const is used to declare global variables whose values will not change. In almost all code (and particularly performance sensitive code) global variables should be declared constant in this way.
1. const x = 5
Multiple variables can be declared within a single const:
1. const y, z = 7, 11
Note that const only applies to one = operation, therefore const x = y = 1 declares x to be constant but not y. On the other hand, const x = const y = 1 declares both x and y constant.
Note that “constant-ness” does not extend into mutable containers; only the association between a variable and its value is constant. If x is an array or dictionary (for example) you can still modify, add, or remove elements.
In some cases changing the value of a const variable gives a warning instead of an error. However, this can produce unpredictable behavior or corrupt the state of your program, and so should be avoided. This feature is intended only for convenience during interactive use.
struct — Keyword
1. struct
The most commonly used kind of type in Julia is a struct, specified as a name and a set of fields.
1. struct Point
2. x
3. y
4. end
Fields can have type restrictions, which may be parameterized:
1. struct Point{X}
2. x::X
3. y::Float64
4. end
A struct can also declare an abstract super type via <: syntax:
1. struct Point <: AbstractPoint
2. x
3. y
4. end
structs are immutable by default; an instance of one of these types cannot be modified after construction. Use mutable struct instead to declare a type whose instances can be modified.
See the manual section on Composite Types for more details, such as how to define constructors.
mutable struct — Keyword
1. mutable struct
mutable struct is similar to struct, but additionally allows the fields of the type to be set after construction. See the manual section on Composite Types for more information.
abstract type — Keyword
1. abstract type
abstract type declares a type that cannot be instantiated, and serves only as a node in the type graph, thereby describing sets of related concrete types: those concrete types which are their descendants. Abstract types form the conceptual hierarchy which makes Julia’s type system more than just a collection of object implementations. For example:
1. abstract type Number end
2. abstract type Real <: Number end
Number has no supertype, whereas Real is an abstract subtype of Number.
primitive type — Keyword
1. primitive type
primitive type declares a concrete type whose data consists only of a series of bits. Classic examples of primitive types are integers and floating-point values. Some example built-in primitive type declarations:
1. primitive type Char 32 end
2. primitive type Bool <: Integer 8 end
The number after the name indicates how many bits of storage the type requires. Currently, only sizes that are multiples of 8 bits are supported. The Bool declaration shows how a primitive type can be optionally declared to be a subtype of some supertype.
... — Keyword
1. ...
The “splat” operator, ..., represents a sequence of arguments. ... can be used in function definitions, to indicate that the function accepts an arbitrary number of arguments. ... can also be used to apply a function to a sequence of arguments.
Examples
1. julia> add(xs...) = reduce(+, xs)
2. add (generic function with 1 method)
4. julia> add(1, 2, 3, 4, 5)
5. 15
7. julia> add([1, 2, 3]...)
8. 6
10. julia> add(7, 1:100..., 1000:1100...)
11. 111107
; — Keyword
1. ;
; has a similar role in Julia as in many C-like languages, and is used to delimit the end of the previous statement. ; is not necessary after new lines, but can be used to separate statements on a single line or to join statements into a single expression. ; is also used to suppress output printing in the REPL and similar interfaces.
Examples
1. julia> function foo()
2. x = "Hello, "; x *= "World!"
3. return x
4. end
5. foo (generic function with 1 method)
7. julia> bar() = (x = "Hello, Mars!"; return x)
8. bar (generic function with 1 method)
10. julia> foo();
12. julia> bar()
13. "Hello, Mars!"
Base 模块
Base — Module
1. Base
The base library of Julia. Base is a module that contains basic functionality (the contents of base/). All modules implicitly contain using Base, since this is needed in the vast majority of cases.
Base.Broadcast — Module
1. Base.Broadcast
Module containing the broadcasting implementation.
Base.Docs — Module
1. Docs
The Docs module provides the @doc macro which can be used to set and retrieve documentation metadata for Julia objects.
Please see the manual section on documentation for more information.
Base.Iterators — Module
Methods for working with Iterators.
Base.Libc — Module
Interface to libc, the C standard library.
Base.Meta — Module
Convenience functions for metaprogramming.
Base.StackTraces — Module
Tools for collecting and manipulating stack traces. Mainly used for building errors.
Base.Sys — Module
Provide methods for retrieving information about hardware and the operating system.
Base.Threads — Module
Experimental multithreading support.
Base.GC — Module
1. Base.GC
Module with garbage collection utilities.
所有对象
Core.:=== — Function
1. ===(x,y) -> Bool
2. ≡(x,y) -> Bool
Determine whether x and y are identical, in the sense that no program could distinguish them. First the types of x and y are compared. If those are identical, mutable objects are compared by address in memory and immutable objects (such as numbers) are compared by contents at the bit level. This function is sometimes called “egal”. It always returns a Bool value.
Examples
1. julia> a = [1, 2]; b = [1, 2];
3. julia> a == b
4. true
6. julia> a === b
7. false
9. julia> a === a
10. true
Core.isa — Function
1. isa(x, type) -> Bool
Determine whether x is of the given type. Can also be used as an infix operator, e.g. x isa type.
Examples
1. julia> isa(1, Int)
2. true
4. julia> isa(1, Matrix)
5. false
7. julia> isa(1, Char)
8. false
10. julia> isa(1, Number)
11. true
13. julia> 1 isa Number
14. true
Base.isequal — Function
1. isequal(x, y)
Similar to ==, except for the treatment of floating point numbers and of missing values. isequal treats all floating-point NaN values as equal to each other, treats -0.0 as unequal to 0.0, and missing as equal to missing. Always returns a Bool value.
Implementation
The default implementation of isequal calls ==, so a type that does not involve floating-point values generally only needs to define ==.
isequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).
This typically means that types for which a custom == or isequal method exists must implement a corresponding hash method (and vice versa). Collections typically implement isequal by calling isequal recursively on all contents.
Scalar types generally do not need to implement isequal separate from ==, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on isnan, signbit, and ==).
Examples
1. julia> isequal([1., NaN], [1., NaN])
2. true
4. julia> [1., NaN] == [1., NaN]
5. false
7. julia> 0.0 == -0.0
8. true
10. julia> isequal(0.0, -0.0)
11. false
1. isequal(x)
Create a function that compares its argument to x using isequal, i.e. a function equivalent to y -> isequal(y, x).
The returned function is of type Base.Fix2{typeof(isequal)}, which can be used to implement specialized methods.
Base.isless — Function
1. isless(x, y)
Test whether x is less than y, according to a fixed total order. isless is not defined on all pairs of values (x, y). However, if it is defined, it is expected to satisfy the following:
- If
isless(x, y)is defined, then so isisless(y, x)andisequal(x, y), and exactly one of those three yieldstrue. - The relation defined by
islessis transitive, i.e.,isless(x, y) && isless(y, z)impliesisless(x, z).
Values that are normally unordered, such as NaN, are ordered in an arbitrary but consistent fashion. missing values are ordered last.
This is the default comparison used by sort.
Implementation
Non-numeric types with a total order should implement this function. Numeric types only need to implement it if they have special values such as NaN. Types with a partial order should implement <.
Core.ifelse — Function
1. ifelse(condition::Bool, x, y)
Return x if condition is true, otherwise return y. This differs from ? or if in that it is an ordinary function, so all the arguments are evaluated first. In some cases, using ifelse instead of an if statement can eliminate the branch in generated code and provide higher performance in tight loops.
Examples
1. julia> ifelse(1 > 2, 1, 2)
2. 2
Core.typeassert — Function
1. typeassert(x, type)
Throw a TypeError unless x isa type. The syntax x::type calls this function.
Examples
1. julia> typeassert(2.5, Int)
2. ERROR: TypeError: in typeassert, expected Int64, got Float64
3. Stacktrace:
4. [...]
Core.typeof — Function
1. typeof(x)
Get the concrete type of x.
Examples
1. julia> a = 1//2;
3. julia> typeof(a)
4. Rational{Int64}
6. julia> M = [1 2; 3.5 4];
8. julia> typeof(M)
9. Array{Float64,2}
Core.tuple — Function
1. tuple(xs...)
Construct a tuple of the given objects.
Examples
1. julia> tuple(1, 'a', pi)
2. (1, 'a', π)
Base.ntuple — Function
1. ntuple(f::Function, n::Integer)
Create a tuple of length n, computing each element as f(i), where i is the index of the element.
Examples
1. julia> ntuple(i -> 2*i, 4)
2. (2, 4, 6, 8)
Base.objectid — Function
1. objectid(x)
Get a hash value for x based on object identity. objectid(x)==objectid(y) if x === y.
Base.hash — Function
1. hash(x[, h::UInt])
Compute an integer hash code such that isequal(x,y) implies hash(x)==hash(y). The optional second argument h is a hash code to be mixed with the result.
New types should implement the 2-argument form, typically by calling the 2-argument hash method recursively in order to mix hashes of the contents with each other (and with h). Typically, any type that implements hash should also implement its own == (hence isequal) to guarantee the property mentioned above. Types supporting subtraction (operator -) should also implement widen, which is required to hash values inside heterogeneous arrays.
Base.finalizer — Function
1. finalizer(f, x)
Register a function f(x) to be called when there are no program-accessible references to x, and return x. The type of x must be a mutable struct, otherwise the behavior of this function is unpredictable.
f must not cause a task switch, which excludes most I/O operations such as println. @schedule println("message") or ccall(:jl_, Void, (Any,), "message") may be helpful for debugging purposes.
Base.finalize — Function
1. finalize(x)
Immediately run finalizers registered for object x.
Base.copy — Function
1. copy(x)
Create a shallow copy of x: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.
Base.deepcopy — Function
1. deepcopy(x)
Create a deep copy of x: everything is copied recursively, resulting in a fully independent object. For example, deep-copying an array produces a new array whose elements are deep copies of the original elements. Calling deepcopy on an object should generally have the same effect as serializing and then deserializing it.
As a special case, functions can only be actually deep-copied if they are anonymous, otherwise they are just copied. The difference is only relevant in the case of closures, i.e. functions which may contain hidden internal references.
While it isn’t normally necessary, user-defined types can override the default deepcopy behavior by defining a specialized version of the function deepcopy_internal(x::T, dict::IdDict) (which shouldn’t otherwise be used), where T is the type to be specialized for, and dict keeps track of objects copied so far within the recursion. Within the definition, deepcopy_internal should be used in place of deepcopy, and the dict variable should be updated as appropriate before returning.
Base.getproperty — Function
1. getproperty(value, name::Symbol)
The syntax a.b calls getproperty(a, :b).
Examples
1. julia> struct MyType
2. x
3. end
5. julia> function Base.getproperty(obj::MyType, sym::Symbol)
6. if sym === :special
7. return obj.x + 1
8. else # fallback to getfield
9. return getfield(obj, sym)
10. end
11. end
13. julia> obj = MyType(1);
15. julia> obj.special
16. 2
18. julia> obj.x
19. 1
See also propertynames and setproperty!.
Base.setproperty! — Function
1. setproperty!(value, name::Symbol, x)
The syntax a.b = c calls setproperty!(a, :b, c).
See also propertynames and getproperty.
Base.propertynames — Function
1. propertynames(x, private=false)
Get a tuple or a vector of the properties (x.property) of an object x. This is typically the same as fieldnames(typeof(x)), but types that overload getproperty should generally overload propertynames as well to get the properties of an instance of the type.
propertynames(x) may return only “public” property names that are part of the documented interface of x. If you want it to also return “private” fieldnames intended for internal use, pass true for the optional second argument. REPL tab completion on x. shows only the private=false properties.
Core.getfield — Function
1. getfield(value, name::Symbol)
Extract a named field from a value of composite type. See also getproperty.
Examples
1. julia> a = 1//2
2. 1//2
4. julia> getfield(a, :num)
5. 1
7. julia> a.num
8. 1
Core.setfield! — Function
1. setfield!(value, name::Symbol, x)
Assign x to a named field in value of composite type. The value must be mutable and x must be a subtype of fieldtype(typeof(value), name). See also setproperty!.
Examples
1. julia> mutable struct MyMutableStruct
2. field::Int
3. end
5. julia> a = MyMutableStruct(1);
7. julia> setfield!(a, :field, 2);
9. julia> getfield(a, :field)
10. 2
12. julia> a = 1//2
13. 1//2
15. julia> setfield!(a, :num, 3);
16. ERROR: setfield! immutable struct of type Rational cannot be changed
Core.isdefined — Function
1. isdefined(m::Module, s::Symbol)
2. isdefined(object, s::Symbol)
3. isdefined(object, index::Int)
Tests whether a global variable or object field is defined. The arguments can be a module and a symbol or a composite object and field name (as a symbol) or index.
To test whether an array element is defined, use isassigned instead.
See also @isdefined.
Examples
1. julia> isdefined(Base, :sum)
2. true
4. julia> isdefined(Base, :NonExistentMethod)
5. false
7. julia> a = 1//2;
9. julia> isdefined(a, 2)
10. true
12. julia> isdefined(a, 3)
13. false
15. julia> isdefined(a, :num)
16. true
18. julia> isdefined(a, :numerator)
19. false
Base.@isdefined — Macro
1. @isdefined s -> Bool
Tests whether variable s is defined in the current scope.
See also isdefined.
Examples
1. julia> function f()
2. println(@isdefined x)
3. x = 3
4. println(@isdefined x)
5. end
6. f (generic function with 1 method)
8. julia> f()
9. false
10. true
Base.convert — Function
1. convert(T, x)
Convert x to a value of type T.
If T is an Integer type, an [InexactError](#C
(本文超出站点单文档体积上限,已截断)
