Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Array slicing
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===1999: [[D programming language|D]]=== Consider the array: <syntaxhighlight lang="d"> int[] a = [2, 5, 7, 3, 8, 6, 4, 1]; </syntaxhighlight> Take a slice out of it: <syntaxhighlight lang="d"> int[] b = a[2 .. 5]; </syntaxhighlight> and the contents of <code>b</code> will be <code>[7, 3, 8]</code>. The first index of the slice is inclusive, the second is exclusive. <syntaxhighlight lang="d"> auto c = a[$ - 4 .. $ - 2]; </syntaxhighlight> means that the dynamic array <code>c</code> now contains <code>[8, 6]</code> because inside the [] the <code>$</code> symbol refers to the length of the array. D array slices are aliased to the original array, so: <syntaxhighlight lang="d"> b[2] = 10; </syntaxhighlight> means that <code>a</code> now has the contents <code>[2, 5, 7, 3, 10, 6, 4, 1]</code>. To create a copy of the array data, instead of only an alias, do: <syntaxhighlight lang="d"> auto b = a[2 .. 5].dup; </syntaxhighlight> Unlike Python, D slice bounds don't saturate, so code equivalent to this Python code is an error in D: <syntaxhighlight lang="pycon"> >>> d = [10, 20, 30] >>> d[1 : 5] [20, 30] </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)