Mojo struct
Slice
struct Slice
Represents a slice expression.
Objects of this type are generated when slice syntax is used within square brackets, e.g.:
var msg: String = "Hello Mojo"
# Both are equivalent and print "Mojo".
print(msg[6:])
print(msg.__getitem__(Slice(6, len(msg))))Fields
- start (Optional[Int]): The starting index of the slice.
- end (Optional[Int]): The end index of the slice.
- step (Optional[Int]): The step increment value of the slice.
Implemented traits
AnyType,
Copyable,
EqualityComparable,
ImplicitlyCopyable,
Movable,
Representable,
Stringable,
UnknownDestructibility,
Writable
Aliases
__copyinit__is_trivial
alias __copyinit__is_trivial = Optional[Int].__copyinit__is_trivial
__del__is_trivial
alias __del__is_trivial = Optional[Int].__del__is_trivial
__moveinit__is_trivial
alias __moveinit__is_trivial = Optional[Int].__moveinit__is_trivial
Methods
__init__
__init__(out self, start: Int, end: Int)
Construct slice given the start and end values.
Args:
__init__(out self, start: Optional[Int], end: Optional[Int], step: Optional[Int])
Construct slice given the start, end and step values.
Args:
__eq__
__eq__(self, other: Self) -> Bool
Compare this slice to the other.
Args:
- other (Self): The slice to compare to.
Returns:
Bool: True if start, end, and step values of this slice match the
corresponding values of the other slice and False otherwise.
__str__
__str__(self) -> String
Gets the string representation of the span.
Returns:
String: The string representation of the span.
__repr__
__repr__(self) -> String
Gets the string representation of the span.
Returns:
String: The string representation of the span.
write_to
write_to(self, mut writer: T)
Write Slice string representation to a Writer.
Args:
- writer (T): The object to write to.
indices
indices(self, length: Int) -> Tuple[Int, Int, Int]
Returns a tuple of 3 integers representing the start, end, and step of the slice if applied to a container of the given length.
Uses the target container length to normalize negative, out of bounds, or None indices.
Negative indices are wrapped using the length of the container.
s = slice(0, -1, 1)
i = s.indices(5) # returns (0, 4, 1)None indices are defaulted to the start or the end of the container
based on whether step is positive or negative.
s = slice(None, None, 1)
i = s.indices(5) # returns (0, 5, 1)Out of bounds indices are clamped using the size of the container.
s = slice(20)
i = s.indices(5) # returns (0, 5, 1)Args:
- length (Int): The length of the target container.
Returns:
Tuple: A tuple containing three integers for start, end, and step.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!
