Merge branch 'master' into patch-1
This commit is contained in:
commit
f386d9bdb7
105
ChangeLog.md
105
ChangeLog.md
|
@ -1,105 +0,0 @@
|
|||
# ChangeLog
|
||||
|
||||
## 2022-03-31
|
||||
|
||||
- Add [Iterator](https://practice.rs/functional-programing/iterator.html)
|
||||
- Add [Newtype and DST](https://practice.rs/newtype-sized.html)
|
||||
|
||||
|
||||
## 2022-03-30
|
||||
|
||||
- Add [Advance Liftime](https://practice.rs/lifetime/advance.html) chapter
|
||||
|
||||
### 2022-03-29
|
||||
|
||||
- Add language switch icon in top-right corner
|
||||
- Add [&'static and T: 'static](https://practice.rs/lifetime/static.html)
|
||||
|
||||
|
||||
### 2022-03-28
|
||||
|
||||
- Add [Basic lifetime](https://practice.rs/lifetime/basic.html)
|
||||
|
||||
### 2022-03-25
|
||||
|
||||
- Replace gitalk with giscus comments system which is based on Github Discussions
|
||||
- Update css styles
|
||||
|
||||
### 2022-03-24
|
||||
|
||||
- Add [comment-docs.md(Zh)]
|
||||
|
||||
### 2022-03-23
|
||||
|
||||
- Add [crate.md(Zh)]
|
||||
- Add [module.md(Zh)]
|
||||
- Add [use-pub.md(Zh)]
|
||||
|
||||
|
||||
### 2022-03-20
|
||||
|
||||
- Add [Result (zh)]
|
||||
- Add [Panics (Zh)]
|
||||
- Add [Type conversion - others.md (zh)]
|
||||
|
||||
### 2022-03-18
|
||||
|
||||
- Add [Type conversion - From and Into( Zh )]
|
||||
|
||||
### 2022-03-17
|
||||
|
||||
- Add [Small projects with Elegant code](https://practice.rs/elegant-code-base.html)
|
||||
|
||||
### 2022-03-15
|
||||
|
||||
- Add [Formatting](https://practice.rs/formatted-output/formatting.html)
|
||||
- Add [prinln! and format!](https://practice.rs/formatted-output/println.html)
|
||||
- Add [Debug and Display](https://practice.rs/formatted-output/debug-display.html)
|
||||
- Add [Comments and Docs](https://practice.rs/comments-docs.html)
|
||||
- Add [Fighting with Compiler](https://practice.rs/fight-compiler/intro.html)
|
||||
|
||||
|
||||
### 2022-03-14
|
||||
|
||||
- Add [Package and Crate](https://practice.rs/crate-module/crate.html)
|
||||
- Add [Modules](https://practice.rs/crate-module/module.html)
|
||||
- Add [Advanced use and pub](https://practice.rs/crate-module/use-pub.html)
|
||||
|
||||
### 2022-03-11
|
||||
|
||||
- Add one exercise in [Patterns](https://practice.rs/pattern-match/patterns.html)
|
||||
- Add [Result and ?](https://practice.rs/result-panic/result.html)
|
||||
|
||||
### 2022-03-10
|
||||
|
||||
- Add [Type conversions - From/Into](https://practice.rs/type-conversions/from-into.html)
|
||||
- Add [Type conversions - Others](https://practice.rs/type-conversions/others.html)
|
||||
- Add [Panics](https://practice.rs/result-panic/panic.html)
|
||||
- Add exercises for [diverging functions](https://practice.rs/basic-types/functions.html#diverging-functions)
|
||||
|
||||
### 2022-03-09
|
||||
|
||||
- Translate several English chapters to Chinese
|
||||
- Add [Type conversions - As](https://practice.rs/type-conversions/as.html)
|
||||
|
||||
### 2022-03-08
|
||||
|
||||
- Add [HashMap](https://practice.rs/collections/hashmap.html)
|
||||
- Translate several English chapters to Chinese
|
||||
|
||||
### 2022-03-07
|
||||
|
||||
- Add [Strings](https://practice.rs/collections/string.html)
|
||||
- Add [Vectors](https://practice.rs/collections/vector.html)
|
||||
|
||||
### 2022-03-06
|
||||
|
||||
- Add [Advanced Traits](https://practice.rs/generics-traits/advanced-traits.html)
|
||||
|
||||
### 2022-03-05
|
||||
|
||||
- Add [Trati object](https://practice.rs/generics-traits/trait-object.html)
|
||||
|
||||
### 2022-03-05
|
||||
|
||||
- Add [Traits chapter](https://practice.rs/generics-traits/traits.html) and solutions
|
532
LICENSE
532
LICENSE
|
@ -1,201 +1,395 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
Attribution 4.0 International
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
=======================================================================
|
||||
|
||||
1. Definitions.
|
||||
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
||||
does not provide legal services or legal advice. Distribution of
|
||||
Creative Commons public licenses does not create a lawyer-client or
|
||||
other relationship. Creative Commons makes its licenses and related
|
||||
information available on an "as-is" basis. Creative Commons gives no
|
||||
warranties regarding its licenses, any material licensed under their
|
||||
terms and conditions, or any related information. Creative Commons
|
||||
disclaims all liability for damages resulting from their use to the
|
||||
fullest extent possible.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
Using Creative Commons Public Licenses
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
Creative Commons public licenses provide a standard set of terms and
|
||||
conditions that creators and other rights holders may use to share
|
||||
original works of authorship and other material subject to copyright
|
||||
and certain other rights specified in the public license below. The
|
||||
following considerations are for informational purposes only, are not
|
||||
exhaustive, and do not form part of our licenses.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
Considerations for licensors: Our public licenses are
|
||||
intended for use by those authorized to give the public
|
||||
permission to use material in ways otherwise restricted by
|
||||
copyright and certain other rights. Our licenses are
|
||||
irrevocable. Licensors should read and understand the terms
|
||||
and conditions of the license they choose before applying it.
|
||||
Licensors should also secure all rights necessary before
|
||||
applying our licenses so that the public can reuse the
|
||||
material as expected. Licensors should clearly mark any
|
||||
material not subject to the license. This includes other CC-
|
||||
licensed material, or material used under an exception or
|
||||
limitation to copyright. More considerations for licensors:
|
||||
wiki.creativecommons.org/Considerations_for_licensors
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
Considerations for the public: By using one of our public
|
||||
licenses, a licensor grants the public permission to use the
|
||||
licensed material under specified terms and conditions. If
|
||||
the licensor's permission is not necessary for any reason--for
|
||||
example, because of any applicable exception or limitation to
|
||||
copyright--then that use is not regulated by the license. Our
|
||||
licenses grant only permissions under copyright and certain
|
||||
other rights that a licensor has authority to grant. Use of
|
||||
the licensed material may still be restricted for other
|
||||
reasons, including because others have copyright or other
|
||||
rights in the material. A licensor may make special requests,
|
||||
such as asking that all changes be marked or described.
|
||||
Although not required by our licenses, you are encouraged to
|
||||
respect those requests where reasonable. More_considerations
|
||||
for the public:
|
||||
wiki.creativecommons.org/Considerations_for_licensees
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
=======================================================================
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
Creative Commons Attribution 4.0 International Public License
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
By exercising the Licensed Rights (defined below), You accept and agree
|
||||
to be bound by the terms and conditions of this Creative Commons
|
||||
Attribution 4.0 International Public License ("Public License"). To the
|
||||
extent this Public License may be interpreted as a contract, You are
|
||||
granted the Licensed Rights in consideration of Your acceptance of
|
||||
these terms and conditions, and the Licensor grants You such rights in
|
||||
consideration of benefits the Licensor receives from making the
|
||||
Licensed Material available under these terms and conditions.
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
Section 1 -- Definitions.
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
a. Adapted Material means material subject to Copyright and Similar
|
||||
Rights that is derived from or based upon the Licensed Material
|
||||
and in which the Licensed Material is translated, altered,
|
||||
arranged, transformed, or otherwise modified in a manner requiring
|
||||
permission under the Copyright and Similar Rights held by the
|
||||
Licensor. For purposes of this Public License, where the Licensed
|
||||
Material is a musical work, performance, or sound recording,
|
||||
Adapted Material is always produced where the Licensed Material is
|
||||
synched in timed relation with a moving image.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
b. Adapter's License means the license You apply to Your Copyright
|
||||
and Similar Rights in Your contributions to Adapted Material in
|
||||
accordance with the terms and conditions of this Public License.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
c. Copyright and Similar Rights means copyright and/or similar rights
|
||||
closely related to copyright including, without limitation,
|
||||
performance, broadcast, sound recording, and Sui Generis Database
|
||||
Rights, without regard to how the rights are labeled or
|
||||
categorized. For purposes of this Public License, the rights
|
||||
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
||||
Rights.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
d. Effective Technological Measures means those measures that, in the
|
||||
absence of proper authority, may not be circumvented under laws
|
||||
fulfilling obligations under Article 11 of the WIPO Copyright
|
||||
Treaty adopted on December 20, 1996, and/or similar international
|
||||
agreements.
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
||||
any other exception or limitation to Copyright and Similar Rights
|
||||
that applies to Your use of the Licensed Material.
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
f. Licensed Material means the artistic or literary work, database,
|
||||
or other material to which the Licensor applied this Public
|
||||
License.
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
g. Licensed Rights means the rights granted to You subject to the
|
||||
terms and conditions of this Public License, which are limited to
|
||||
all Copyright and Similar Rights that apply to Your use of the
|
||||
Licensed Material and that the Licensor has authority to license.
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
h. Licensor means the individual(s) or entity(ies) granting rights
|
||||
under this Public License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
i. Share means to provide material to the public by any means or
|
||||
process that requires permission under the Licensed Rights, such
|
||||
as reproduction, public display, public performance, distribution,
|
||||
dissemination, communication, or importation, and to make material
|
||||
available to the public including in ways that members of the
|
||||
public may access the material from a place and at a time
|
||||
individually chosen by them.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
j. Sui Generis Database Rights means rights other than copyright
|
||||
resulting from Directive 96/9/EC of the European Parliament and of
|
||||
the Council of 11 March 1996 on the legal protection of databases,
|
||||
as amended and/or succeeded, as well as other essentially
|
||||
equivalent rights anywhere in the world.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
k. You means the individual or entity exercising the Licensed Rights
|
||||
under this Public License. Your has a corresponding meaning.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
Section 2 -- Scope.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
a. License grant.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
1. Subject to the terms and conditions of this Public License,
|
||||
the Licensor hereby grants You a worldwide, royalty-free,
|
||||
non-sublicensable, non-exclusive, irrevocable license to
|
||||
exercise the Licensed Rights in the Licensed Material to:
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
a. reproduce and Share the Licensed Material, in whole or
|
||||
in part; and
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
b. produce, reproduce, and Share Adapted Material.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
2. Exceptions and Limitations. For the avoidance of doubt, where
|
||||
Exceptions and Limitations apply to Your use, this Public
|
||||
License does not apply, and You do not need to comply with
|
||||
its terms and conditions.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
3. Term. The term of this Public License is specified in Section
|
||||
6(a).
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
4. Media and formats; technical modifications allowed. The
|
||||
Licensor authorizes You to exercise the Licensed Rights in
|
||||
all media and formats whether now known or hereafter created,
|
||||
and to make technical modifications necessary to do so. The
|
||||
Licensor waives and/or agrees not to assert any right or
|
||||
authority to forbid You from making technical modifications
|
||||
necessary to exercise the Licensed Rights, including
|
||||
technical modifications necessary to circumvent Effective
|
||||
Technological Measures. For purposes of this Public License,
|
||||
simply making modifications authorized by this Section 2(a)
|
||||
(4) never produces Adapted Material.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
5. Downstream recipients.
|
||||
|
||||
a. Offer from the Licensor -- Licensed Material. Every
|
||||
recipient of the Licensed Material automatically
|
||||
receives an offer from the Licensor to exercise the
|
||||
Licensed Rights under the terms and conditions of this
|
||||
Public License.
|
||||
|
||||
b. No downstream restrictions. You may not offer or impose
|
||||
any additional or different terms or conditions on, or
|
||||
apply any Effective Technological Measures to, the
|
||||
Licensed Material if doing so restricts exercise of the
|
||||
Licensed Rights by any recipient of the Licensed
|
||||
Material.
|
||||
|
||||
6. No endorsement. Nothing in this Public License constitutes or
|
||||
may be construed as permission to assert or imply that You
|
||||
are, or that Your use of the Licensed Material is, connected
|
||||
with, or sponsored, endorsed, or granted official status by,
|
||||
the Licensor or others designated to receive attribution as
|
||||
provided in Section 3(a)(1)(A)(i).
|
||||
|
||||
b. Other rights.
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not
|
||||
licensed under this Public License, nor are publicity,
|
||||
privacy, and/or other similar personality rights; however, to
|
||||
the extent possible, the Licensor waives and/or agrees not to
|
||||
assert any such rights held by the Licensor to the limited
|
||||
extent necessary to allow You to exercise the Licensed
|
||||
Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this
|
||||
Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to
|
||||
collect royalties from You for the exercise of the Licensed
|
||||
Rights, whether directly or through a collecting society
|
||||
under any voluntary or waivable statutory or compulsory
|
||||
licensing scheme. In all other cases the Licensor expressly
|
||||
reserves any right to collect such royalties.
|
||||
|
||||
|
||||
Section 3 -- License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the
|
||||
following conditions.
|
||||
|
||||
a. Attribution.
|
||||
|
||||
1. If You Share the Licensed Material (including in modified
|
||||
form), You must:
|
||||
|
||||
a. retain the following if it is supplied by the Licensor
|
||||
with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed
|
||||
Material and any others designated to receive
|
||||
attribution, in any reasonable manner requested by
|
||||
the Licensor (including by pseudonym if
|
||||
designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of
|
||||
warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the
|
||||
extent reasonably practicable;
|
||||
|
||||
b. indicate if You modified the Licensed Material and
|
||||
retain an indication of any previous modifications; and
|
||||
|
||||
c. indicate the Licensed Material is licensed under this
|
||||
Public License, and include the text of, or the URI or
|
||||
hyperlink to, this Public License.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any
|
||||
reasonable manner based on the medium, means, and context in
|
||||
which You Share the Licensed Material. For example, it may be
|
||||
reasonable to satisfy the conditions by providing a URI or
|
||||
hyperlink to a resource that includes the required
|
||||
information.
|
||||
|
||||
3. If requested by the Licensor, You must remove any of the
|
||||
information required by Section 3(a)(1)(A) to the extent
|
||||
reasonably practicable.
|
||||
|
||||
4. If You Share Adapted Material You produce, the Adapter's
|
||||
License You apply must not prevent recipients of the Adapted
|
||||
Material from complying with this Public License.
|
||||
|
||||
|
||||
Section 4 -- Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that
|
||||
apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
||||
to extract, reuse, reproduce, and Share all or a substantial
|
||||
portion of the contents of the database;
|
||||
|
||||
b. if You include all or a substantial portion of the database
|
||||
contents in a database in which You have Sui Generis Database
|
||||
Rights, then the database in which You have Sui Generis Database
|
||||
Rights (but not its individual contents) is Adapted Material; and
|
||||
|
||||
c. You must comply with the conditions in Section 3(a) if You Share
|
||||
all or a substantial portion of the contents of the database.
|
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not
|
||||
replace Your obligations under this Public License where the Licensed
|
||||
Rights include other Copyright and Similar Rights.
|
||||
|
||||
|
||||
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
||||
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
||||
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
||||
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
||||
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
||||
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
||||
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
||||
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
||||
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
||||
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
||||
|
||||
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
||||
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
||||
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
||||
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
||||
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
||||
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
||||
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
||||
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
||||
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided
|
||||
above shall be interpreted in a manner that, to the extent
|
||||
possible, most closely approximates an absolute disclaimer and
|
||||
waiver of all liability.
|
||||
|
||||
|
||||
Section 6 -- Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and
|
||||
Similar Rights licensed here. However, if You fail to comply with
|
||||
this Public License, then Your rights under this Public License
|
||||
terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under
|
||||
Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided
|
||||
it is cured within 30 days of Your discovery of the
|
||||
violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any
|
||||
right the Licensor may have to seek remedies for Your violations
|
||||
of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the
|
||||
Licensed Material under separate terms or conditions or stop
|
||||
distributing the Licensed Material at any time; however, doing so
|
||||
will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
||||
License.
|
||||
|
||||
|
||||
Section 7 -- Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different
|
||||
terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the
|
||||
Licensed Material not stated herein are separate from and
|
||||
independent of the terms and conditions of this Public License.
|
||||
|
||||
|
||||
Section 8 -- Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and
|
||||
shall not be interpreted to, reduce, limit, restrict, or impose
|
||||
conditions on any use of the Licensed Material that could lawfully
|
||||
be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is
|
||||
deemed unenforceable, it shall be automatically reformed to the
|
||||
minimum extent necessary to make it enforceable. If the provision
|
||||
cannot be reformed, it shall be severed from this Public License
|
||||
without affecting the enforceability of the remaining terms and
|
||||
conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no
|
||||
failure to comply consented to unless expressly agreed to by the
|
||||
Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted
|
||||
as a limitation upon, or waiver of, any privileges and immunities
|
||||
that apply to the Licensor or You, including from the legal
|
||||
processes of any jurisdiction or authority.
|
||||
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons is not a party to its public
|
||||
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
||||
its public licenses to material it publishes and in those instances
|
||||
will be considered the "Licensor." The text of the Creative Commons
|
||||
public licenses is dedicated to the public domain under the CC0 Public
|
||||
Domain Dedication. Except for the limited purpose of indicating that
|
||||
material is shared under a Creative Commons public license or as
|
||||
otherwise permitted by the Creative Commons policies published at
|
||||
creativecommons.org/policies, Creative Commons does not authorize the
|
||||
use of the trademark "Creative Commons" or any other trademark or logo
|
||||
of Creative Commons without its prior written consent including,
|
||||
without limitation, in connection with any unauthorized modifications
|
||||
to any of its public licenses or any other arrangements,
|
||||
understandings, or agreements concerning use of licensed material. For
|
||||
the avoidance of doubt, this paragraph does not form part of the
|
||||
public licenses.
|
||||
|
||||
Creative Commons may be contacted at creativecommons.org.
|
||||
|
|
64
Readme.md
64
Readme.md
|
@ -1,5 +1,5 @@
|
|||
<div align="center">
|
||||
<img height="150" src="https://github.com/sunface/rust-by-practice/blob/master/en/assets/logo.png">
|
||||
<img src="https://github.com/sunface/rust-by-practice/blob/master/en/assets/header.jpg?raw=true">
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
|
@ -12,8 +12,9 @@
|
|||
|
||||
<div align="center">
|
||||
|
||||
[![Stars Count](https://img.shields.io/github/stars/sunface/rust-by-practice?style=flat)](https://github.com/sunface/rust-by-practice/stargazers) [![Forks Count](https://img.shields.io/github/forks/sunface/rust-by-practice.svg?style=flat)](https://github.com/naaive/orange/network/members)
|
||||
[![LICENSE](https://img.shields.io/badge/license-mit-green?style=flat)](https://github.com/sunface/rust-by-practice/blob/master/LICENSE)
|
||||
[![Stars Count](https://img.shields.io/github/stars/sunface/rust-by-practice?style=flat)](https://github.com/sunface/rust-by-practice/stargazers)
|
||||
[![studyrut](https://img.shields.io/badge/RustCn-orange)](https://hirust.cn)
|
||||
[![LICENSE](https://img.shields.io/badge/license-CC_BY_4.0-green?style=flat)](https://github.com/sunface/rust-by-practice/blob/master/LICENSE)
|
||||
</div>
|
||||
|
||||
This book was designed for easily diving into and get skilled with Rust, and it's very easy to use: All you need to do is to make each exercise compile without ERRORS and Panics !
|
||||
|
@ -23,6 +24,45 @@ This book was designed for easily diving into and get skilled with Rust, and it'
|
|||
|
||||
- [https://practice.rs](https://practice.rs)
|
||||
|
||||
## Features
|
||||
|
||||
Part of our examples and exercises are borrowed from [Rust By Example](https://github.com/rust-lang/rust-by-example), thanks for your great works!
|
||||
|
||||
Although they are so awesome, we have our own secret weapons :)
|
||||
|
||||
- There are three parts in each chapter: examples, exercises and practices
|
||||
|
||||
- Besides examples, we have `a lot of exercises`, you can Read, Edit and Run them ONLINE
|
||||
|
||||
- Covering nearly all aspects of Rust, such as async/await, threads, sync primitives, optimizing, standard libraries, tool chain, data structures and algorithms etc.
|
||||
|
||||
- Every exercise has its own solutions
|
||||
|
||||
- The overall difficulties are a bit higher and from easy to super hard: easy 🌟 medium 🌟🌟 hard 🌟🌟🌟 super hard 🌟🌟🌟🌟
|
||||
|
||||
**What we want to do is fill in the gap between learning and getting started with real projects.**
|
||||
|
||||
## 🏅 Contributors
|
||||
|
||||
Thanks to all of our [contributors](https://github.com/sunface/rust-by-practice/graphs/contributors)!
|
||||
|
||||
<br />
|
||||
|
||||
**🏆 Special thanks to our English editor:**
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<a href="https://github.com/Tanish-Eagle">
|
||||
<img src="https://avatars.githubusercontent.com/u/71984506?v=4?s=100" width="160px" alt=""/>
|
||||
<br />
|
||||
<sub><b>Tanish-Eagle</b></sub>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<br />
|
||||
|
||||
## Running locally
|
||||
|
||||
We use [mdbook](https://rust-lang.github.io/mdBook/) building our exercises. You can run locally with below steps:
|
||||
|
@ -46,24 +86,6 @@ $ cd rust-by-practice && mdbook serve en/
|
|||
$ cd rust-by-practice && mdbook serve zh-CN/
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
Part of our examples and exercises are borrowed from [Rust By Example](https://github.com/rust-lang/rust-by-example), thanks for your great works!
|
||||
|
||||
Although they are so awesome, we have our own secret weapons :)
|
||||
|
||||
- There are three parts in each chapter: examples, exercises and practices
|
||||
|
||||
- Besides examples, we have `a lot of exercises`, you can Read, Edit and Run them ONLINE
|
||||
|
||||
- Covering nearly all aspects of Rust, such as async/await, threads, sync primitives, optimizing, standard libraries, tool chain, data structures and algorithms etc.
|
||||
|
||||
- Every exercise has its own solutions
|
||||
|
||||
- The overall difficulties are a bit higher and from easy to super hard: easy 🌟 medium 🌟🌟 hard 🌟🌟🌟 super hard 🌟🌟🌟🌟
|
||||
|
||||
**What we want to do is fill in the gap between learning and getting started with real projects.**
|
||||
|
||||
## Some of our exercises
|
||||
|
||||
🌟🌟🌟 Tuple struct looks similar to tuples, it has added meaning the struct name provides but has no named fields. It's useful when you want give the whole tuple a name, but don't care the fields's names.
|
||||
|
|
Binary file not shown.
After Width: | Height: | Size: 34 KiB |
Binary file not shown.
After Width: | Height: | Size: 59 KiB |
|
@ -4,7 +4,7 @@
|
|||
1. 🌟
|
||||
```rust, editable
|
||||
|
||||
// make it work
|
||||
// Make it work
|
||||
use std::mem::size_of_val;
|
||||
fn main() {
|
||||
let c1 = 'a';
|
||||
|
@ -13,14 +13,14 @@ fn main() {
|
|||
let c2 = '中';
|
||||
assert_eq!(size_of_val(&c2),3);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
2. 🌟
|
||||
```rust, editable
|
||||
|
||||
// make it work
|
||||
// Make it work
|
||||
fn main() {
|
||||
let c1 = "中";
|
||||
print_char(c1);
|
||||
|
@ -35,13 +35,13 @@ fn print_char(c : char) {
|
|||
3. 🌟
|
||||
```rust, editable
|
||||
|
||||
// make println! work
|
||||
// Make println! work
|
||||
fn main() {
|
||||
let _f: bool = false;
|
||||
|
||||
let t = true;
|
||||
if !t {
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -49,13 +49,13 @@ fn main() {
|
|||
4. 🌟
|
||||
```rust, editable
|
||||
|
||||
// make it work
|
||||
// Make it work
|
||||
fn main() {
|
||||
let f = true;
|
||||
let t = true && false;
|
||||
assert_eq!(t, f);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -64,36 +64,36 @@ fn main() {
|
|||
5. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// make it work, don't modify `implicitly_ret_unit` !
|
||||
// Make it work, don't modify `implicitly_ret_unit` !
|
||||
fn main() {
|
||||
let _v: () = ();
|
||||
|
||||
let v = (2, 3);
|
||||
assert_eq!(v, implicitly_ret_unit());
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn implicitly_ret_unit() {
|
||||
println!("I will return a ()")
|
||||
println!("I will return a ()");
|
||||
}
|
||||
|
||||
// don't use this one
|
||||
// Don't use this one
|
||||
fn explicitly_ret_unit() -> () {
|
||||
println!("I will return a ()")
|
||||
println!("I will return a ()");
|
||||
}
|
||||
```
|
||||
|
||||
6. 🌟🌟 what's the size of the unit type?
|
||||
6. 🌟🌟 What's the size of the unit type?
|
||||
```rust,editable
|
||||
|
||||
// modify `4` in assert to make it work
|
||||
// Modify `4` in assert to make it work
|
||||
use std::mem::size_of_val;
|
||||
fn main() {
|
||||
let unit: () = ();
|
||||
assert!(size_of_val(&unit) == 4);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -3,13 +3,13 @@
|
|||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
// don't modify the following two lines!
|
||||
// Don't modify the following two lines!
|
||||
let (x, y) = (1, 2);
|
||||
let s = sum(x, y);
|
||||
|
||||
assert_eq!(s, 3);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn sum(x, y: i32) {
|
||||
|
@ -24,9 +24,9 @@ fn main() {
|
|||
print();
|
||||
}
|
||||
|
||||
// replace i32 with another type
|
||||
// Replace i32 with another type
|
||||
fn print() -> i32 {
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -34,16 +34,16 @@ fn print() -> i32 {
|
|||
3. 🌟🌟🌟
|
||||
|
||||
```rust,editable
|
||||
// solve it in two ways
|
||||
// Solve it in two ways
|
||||
// DON'T let `println!` works
|
||||
fn main() {
|
||||
never_return();
|
||||
|
||||
println!("Failed!")
|
||||
println!("Failed!");
|
||||
}
|
||||
|
||||
fn never_return() -> ! {
|
||||
// implement this function, don't modify the fn signatures
|
||||
// Implement this function, don't modify the fn signatures
|
||||
|
||||
}
|
||||
```
|
||||
|
@ -90,11 +90,11 @@ fn main() {
|
|||
// Diverging functions can also be used in match expression to replace a value of any value
|
||||
false => {
|
||||
println!("Success!");
|
||||
panic!("we have no value for `false`, but we can panic")
|
||||
panic!("we have no value for `false`, but we can panic");
|
||||
}
|
||||
};
|
||||
|
||||
println!("Excercise Failed if printing out this line!");
|
||||
println!("Exercise Failed if printing out this line!");
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -4,49 +4,49 @@
|
|||
|
||||
1. 🌟
|
||||
|
||||
> Tips: If we don't explicitly give one type to a varible, then the compiler will infer one for us
|
||||
> Tips: If we don't explicitly assign a type to a variable, then the compiler will infer one for us.
|
||||
|
||||
```rust,editable
|
||||
|
||||
// remove something to make it work
|
||||
// Remove something to make it work
|
||||
fn main() {
|
||||
let x: i32 = 5;
|
||||
let mut y: u32 = 5;
|
||||
|
||||
y = x;
|
||||
|
||||
let z = 10; // type of z ?
|
||||
let z = 10; // Type of z ?
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
2. 🌟
|
||||
```rust,editable
|
||||
|
||||
// fill the blank
|
||||
// Fill the blank
|
||||
fn main() {
|
||||
let v: u16 = 38_u8 as __;
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
3. 🌟🌟🌟
|
||||
|
||||
> Tips: If we don't explicitly give one type to a varible, then the compiler will infer one for us
|
||||
> Tips: If we don't explicitly assign a type to a variable, then the compiler will infer one for us.
|
||||
|
||||
```rust,editable
|
||||
|
||||
// modify `assert_eq!` to make it work
|
||||
// Modify `assert_eq!` to make it work
|
||||
fn main() {
|
||||
let x = 5;
|
||||
assert_eq!("u32".to_string(), type_of(&x));
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
// get the type of given variable, return a string representation of the type , e.g "i8", "u8", "i32", "u32"
|
||||
// Get the type of given variable, return a string representation of the type , e.g "i8", "u8", "i32", "u32"
|
||||
fn type_of<T>(_: &T) -> String {
|
||||
format!("{}", std::any::type_name::<T>())
|
||||
}
|
||||
|
@ -55,19 +55,19 @@ fn type_of<T>(_: &T) -> String {
|
|||
4. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fill the blanks to make it work
|
||||
// Fill the blanks to make it work
|
||||
fn main() {
|
||||
assert_eq!(i8::MAX, __);
|
||||
assert_eq!(u8::MAX, __);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
5. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fix errors and panics to make it work
|
||||
// Fix errors and panics to make it work
|
||||
fn main() {
|
||||
let v1 = 251_u8 + 8;
|
||||
let v2 = i8::checked_add(251, 8).unwrap();
|
||||
|
@ -78,12 +78,12 @@ fn main() {
|
|||
6. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// modify `assert!` to make it work
|
||||
// Modify `assert!` to make it work
|
||||
fn main() {
|
||||
let v = 1_024 + 0xff + 0o77 + 0b1111_1111;
|
||||
assert!(v == 1579);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -93,29 +93,29 @@ fn main() {
|
|||
|
||||
```rust,editable
|
||||
|
||||
// replace ? with your answer
|
||||
// Replace ? with your answer
|
||||
fn main() {
|
||||
let x = 1_000.000_1; // ?
|
||||
let y: f32 = 0.12; // f32
|
||||
let z = 0.01_f64; // f64
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
1. 🌟🌟 make it work in two distinct ways
|
||||
1. 🌟🌟 Make it work in two distinct ways
|
||||
|
||||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
assert!(0.1+0.2==0.3);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
### Range
|
||||
9. 🌟🌟 two goals: 1. modify `assert!` to make it work 2. make `println!` output: 97 - 122
|
||||
9. 🌟🌟 Two goals: 1. Modify `assert!` to make it work 2. Make `println!` output: 97 - 122
|
||||
|
||||
```rust,editable
|
||||
fn main() {
|
||||
|
@ -135,13 +135,13 @@ fn main() {
|
|||
10. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fill the blanks
|
||||
// Fill the blanks
|
||||
use std::ops::{Range, RangeInclusive};
|
||||
fn main() {
|
||||
assert_eq!((1..__), Range{ start: 1, end: 5 });
|
||||
assert_eq!((1..__), RangeInclusive::new(1, 5));
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -150,7 +150,7 @@ fn main() {
|
|||
11. 🌟
|
||||
```rust,editable
|
||||
|
||||
// fill the blanks and fix the errors
|
||||
// Fill the blanks and fix the errors
|
||||
fn main() {
|
||||
// Integer addition
|
||||
assert!(1u32 + 2 == __);
|
||||
|
|
|
@ -27,7 +27,7 @@ fn main() {
|
|||
### Exercises
|
||||
1. 🌟🌟
|
||||
```rust,editable
|
||||
// make it work with two ways
|
||||
// Make it work with two ways
|
||||
fn main() {
|
||||
let v = {
|
||||
let mut x = 1;
|
||||
|
@ -36,7 +36,7 @@ fn main() {
|
|||
|
||||
assert_eq!(v, 3);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -48,7 +48,7 @@ fn main() {
|
|||
|
||||
assert!(v == 3);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -59,7 +59,7 @@ fn main() {
|
|||
let s = sum(1 , 2);
|
||||
assert_eq!(s, 3);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn sum(x: i32, y: i32) -> i32 {
|
||||
|
|
|
@ -9,7 +9,7 @@ The hash table implementation is a Rust port of Google’s [SwissTable](https://
|
|||
### Basic Operations
|
||||
1. 🌟🌟
|
||||
|
||||
```rust,editbale
|
||||
```rust,editable
|
||||
|
||||
// FILL in the blanks and FIX the erros
|
||||
use std::collections::HashMap;
|
||||
|
|
|
@ -1,26 +1,26 @@
|
|||
# Array
|
||||
The type of array is `[T; Lengh]`, as you can see, array's lengh is part of their type signature. So their length must be known at compile time.
|
||||
The type of array is `[T; Length]`, as you can see, array's length is part of their type signature. So their length must be known at compile time.
|
||||
|
||||
For example, you cant initialized an array as below:
|
||||
For example, you cant initialize an array like below:
|
||||
```rust
|
||||
fn init_arr(n: i32) {
|
||||
let arr = [1; n];
|
||||
}
|
||||
```
|
||||
|
||||
This will cause an error, because the compile have no idea of the exact size of the array in compile time.
|
||||
This will cause an error, because the compiler has no idea of the exact size of the array at compile time.
|
||||
|
||||
1. 🌟
|
||||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
// fill the blank with proper array type
|
||||
// Fill the blank with proper array type
|
||||
let arr: __ = [1, 2, 3, 4, 5];
|
||||
|
||||
// modify below to make it work
|
||||
// Modify the code below to make it work
|
||||
assert!(arr.len() == 4);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -28,16 +28,16 @@ fn main() {
|
|||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
// we can ignore parts of the array type or even the whole type, let the compiler infer it for us
|
||||
// We can ignore parts of the array type or even the whole type, let the compiler infer it for us
|
||||
let arr0 = [1, 2, 3];
|
||||
let arr: [_; 3] = ['a', 'b', 'c'];
|
||||
|
||||
// fill the blank
|
||||
// Arrays are stack allocated, `std::mem::size_of_val` return the bytes which array occupies
|
||||
// A char takes 4 byte in Rust: Unicode char
|
||||
// Fill the blank
|
||||
// Arrays are stack allocated, `std::mem::size_of_val` returns the bytes which an array occupies
|
||||
// A char takes 4 bytes in Rust: Unicode char
|
||||
assert!(std::mem::size_of_val(&arr) == __);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -46,13 +46,13 @@ fn main() {
|
|||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
// fill the blank
|
||||
// Fill the blank
|
||||
let list: [i32; 100] = __ ;
|
||||
|
||||
assert!(list[0] == 1);
|
||||
assert!(list.len() == 100);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -60,10 +60,10 @@ fn main() {
|
|||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
// fix the error
|
||||
// Fix the error
|
||||
let _arr = [1, 2, '3'];
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -73,28 +73,28 @@ fn main() {
|
|||
fn main() {
|
||||
let arr = ['a', 'b', 'c'];
|
||||
|
||||
let ele = arr[1]; // only modify this line to make the code work!
|
||||
let ele = arr[1]; // Only modify this line to make the code work!
|
||||
|
||||
assert!(ele == 'a');
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
6. 🌟 Out of bounds indexing causes `panic`.
|
||||
```rust,editable
|
||||
|
||||
// fix the error
|
||||
// Fix the error
|
||||
fn main() {
|
||||
let names = [String::from("Sunfei"), "Sunface".to_string()];
|
||||
|
||||
// `get` returns an Option<T>, it's safe to use
|
||||
// `Get` returns an Option<T>, it's safe to use
|
||||
let name0 = names.get(0).unwrap();
|
||||
|
||||
// but indexing is not safe
|
||||
// But indexing is not safe
|
||||
let _name1 = &names[2];
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
```
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
```rust,editable
|
||||
|
||||
// fix the errors
|
||||
// Fix the errors
|
||||
enum Number {
|
||||
Zero,
|
||||
One,
|
||||
|
@ -25,18 +25,18 @@ enum Number2 {
|
|||
|
||||
|
||||
fn main() {
|
||||
// a enum variant can be converted to a integer by `as`
|
||||
// An enum variant can be converted to a integer by `as`
|
||||
assert_eq!(Number::One, Number1::One);
|
||||
assert_eq!(Number1::One, Number2::One);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
2. 🌟 each enum variant can hold its own data.
|
||||
2. 🌟 Each enum variant can hold its own data.
|
||||
```rust,editable
|
||||
|
||||
// fill in the blank
|
||||
// Fill in the blank
|
||||
enum Message {
|
||||
Quit,
|
||||
Move { x: i32, y: i32 },
|
||||
|
@ -45,17 +45,17 @@ enum Message {
|
|||
}
|
||||
|
||||
fn main() {
|
||||
let msg1 = Message::Move{__}; // instantiating with x = 1, y = 2
|
||||
let msg2 = Message::Write(__); // instantiating with "hello, world!"
|
||||
let msg1 = Message::Move{__}; // Instantiating with x = 1, y = 2
|
||||
let msg2 = Message::Write(__); // Instantiating with "hello, world!"
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
3. 🌟🌟 we can get the data which a enum variant is holding by pattern match
|
||||
3. 🌟🌟 We can get the data which an enum variant is holding by pattern match.
|
||||
```rust,editable
|
||||
|
||||
// fill in the blank and fix the error
|
||||
// Fill in the blank and fix the error
|
||||
enum Message {
|
||||
Quit,
|
||||
Move { x: i32, y: i32 },
|
||||
|
@ -72,7 +72,7 @@ fn main() {
|
|||
panic!("NEVER LET THIS RUN!");
|
||||
}
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -80,7 +80,7 @@ fn main() {
|
|||
|
||||
```rust,editable
|
||||
|
||||
// fill in the blank and fix the errors
|
||||
// Fill in the blank and fix the errors
|
||||
enum Message {
|
||||
Quit,
|
||||
Move { x: i32, y: i32 },
|
||||
|
@ -105,11 +105,11 @@ fn show_message(msg: Message) {
|
|||
}
|
||||
```
|
||||
|
||||
5. 🌟🌟 As there is no `null` in Rust, we have to use enum `Option<T>` to deal the cases when value is absent.
|
||||
5. 🌟🌟 Since there is no `null` in Rust, we have to use enum `Option<T>` to deal with the cases when the value is absent.
|
||||
```rust,editable
|
||||
|
||||
// fill in the blank to make the `println` work.
|
||||
// also add some code to prevent the `panic` from running.
|
||||
// Fill in the blank to make the `println` work.
|
||||
// Also add some code to prevent the `panic` from running.
|
||||
fn main() {
|
||||
let five = Some(5);
|
||||
let six = plus_one(five);
|
||||
|
@ -118,7 +118,7 @@ fn main() {
|
|||
if let __ = six {
|
||||
println!("{}", n);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
panic!("NEVER LET THIS RUN!");
|
||||
|
@ -133,7 +133,7 @@ fn plus_one(x: Option<i32>) -> Option<i32> {
|
|||
```
|
||||
|
||||
|
||||
6. 🌟🌟🌟🌟 implement a `linked-list` via enums.
|
||||
6. 🌟🌟🌟🌟 Implement a `linked-list` via enums.
|
||||
|
||||
```rust,editable
|
||||
|
||||
|
@ -166,12 +166,12 @@ impl List {
|
|||
// depends on the variant of `self`
|
||||
// `self` has type `&List`, and `*self` has type `List`, matching on a
|
||||
// concrete type `T` is preferred over a match on a reference `&T`
|
||||
// after Rust 2018 you can use self here and tail (with no ref) below as well,
|
||||
// After Rust 2018 you can use self here and tail (with no ref) below as well,
|
||||
// rust will infer &s and ref tail.
|
||||
// See https://doc.rust-lang.org/edition-guide/rust-2018/ownership-and-lifetimes/default-match-bindings.html
|
||||
match *self {
|
||||
// Can't take ownership of the tail, because `self` is borrowed;
|
||||
// instead take a reference to the tail
|
||||
// Instead take a reference to the tail
|
||||
Cons(_, ref tail) => 1 + tail.len(),
|
||||
// Base Case: An empty list has zero length
|
||||
Nil => 0
|
||||
|
|
|
@ -4,18 +4,18 @@ Slices are similar to arrays, but their length is not known at compile time, so
|
|||
1. 🌟🌟 Here, both `[i32]` and `str` are slice types, but directly using it will cause errors. You have to use the reference of the slice instead: `&[i32]`, `&str`.
|
||||
```rust,editable
|
||||
|
||||
// fix the errors, DON'T add new lines!
|
||||
// Fix the errors, DON'T add new lines!
|
||||
fn main() {
|
||||
let arr = [1, 2, 3];
|
||||
let s1: [i32] = arr[0..2];
|
||||
|
||||
let s2: str = "hello, world" as str;
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
A slice reference is a two-word object, for simplicity reasons, from now on we will use slice instead of `slice reference`. The first word is a pointer to the data, and the second word is the length of the slice. The word size is the same as usize, determined by the processor architecture eg 64 bits on an x86-64. Slices can be used to borrow a section of an array, and have the type signature `&[T]`.
|
||||
A slice reference is a two-word object, for simplicity reasons, from now on we will use slice instead of `slice reference`. The first word is a pointer to the data, and the second word is the length of the slice. The word size is the same as usize, determined by the processor architecture, eg 64 bits on an x86-64. Slices can be used to borrow a section of an array, and have the type signature `&[T]`.
|
||||
|
||||
2. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
@ -25,11 +25,11 @@ fn main() {
|
|||
|
||||
let slice = &arr[..2];
|
||||
|
||||
// modify '6' to make it work
|
||||
// TIPS: slice( reference ) IS NOT an array, if it is an array, then `assert!` will passed: each of the two UTF-8 chars '中' and '国' occupies 3 bytes, 2 * 3 = 6
|
||||
// Modify '6' to make it work
|
||||
// TIPS: slice( reference ) IS NOT an array, if it is an array, then `assert!` will passed: Each of the two UTF-8 chars '中' and '国' occupies 3 bytes, 2 * 3 = 6
|
||||
assert!(std::mem::size_of_val(&slice) == 6);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -38,15 +38,15 @@ fn main() {
|
|||
|
||||
fn main() {
|
||||
let arr: [i32; 5] = [1, 2, 3, 4, 5];
|
||||
// fill the blanks to make the code work
|
||||
// Fill the blanks to make the code work
|
||||
let slice: __ = __;
|
||||
assert_eq!(slice, &[2, 3, 4]);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
### string slices
|
||||
### String slices
|
||||
4. 🌟
|
||||
```rust,editable
|
||||
|
||||
|
@ -54,12 +54,12 @@ fn main() {
|
|||
let s = String::from("hello");
|
||||
|
||||
let slice1 = &s[0..2];
|
||||
// fill the blank to make the code work, DON'T USE 0..2 again
|
||||
// Fill the blank to make the code work, DON'T USE 0..2 again
|
||||
let slice2 = &s[__];
|
||||
|
||||
assert_eq!(slice1, slice2);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -68,24 +68,24 @@ fn main() {
|
|||
|
||||
fn main() {
|
||||
let s = "你好,世界";
|
||||
// modify this line to make the code work
|
||||
// Modify this line to make the code work
|
||||
let slice = &s[0..2];
|
||||
|
||||
assert!(slice == "你");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
6. 🌟🌟 `&String` can be implicitly converted into `&str`.
|
||||
```rust,editable
|
||||
|
||||
// fix errors
|
||||
// Fix errors
|
||||
fn main() {
|
||||
let mut s = String::from("hello world");
|
||||
|
||||
// here, &s is `&String` type, but `first_word` need a `&str` type.
|
||||
// it works because `&String` can be implicitly converted to `&str, If you want know more ,this is called `Deref`
|
||||
// Here, &s is `&String` type, but `first_word` need a `&str` type.
|
||||
// It works because `&String` can be implicitly converted to `&str, If you want know more ,this is called `Deref`
|
||||
let word = first_word(&s);
|
||||
|
||||
s.clear(); // error!
|
||||
|
|
|
@ -1,17 +1,17 @@
|
|||
# string
|
||||
# String
|
||||
The type of string literal `"hello, world"` is `&str`, e.g `let s: &str = "hello, world"`.
|
||||
|
||||
|
||||
### str and &str
|
||||
1. 🌟 We can't use `str` type in normal ways, but we can use `&str`
|
||||
### Str and &str
|
||||
1. 🌟 We can't use `str` type in normal ways, but we can use `&str`.
|
||||
|
||||
```rust,editable
|
||||
|
||||
// fix error without adding new line
|
||||
// Fix error without adding new line
|
||||
fn main() {
|
||||
let s: str = "hello, world";
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -20,9 +20,9 @@ fn main() {
|
|||
|
||||
```rust,editable
|
||||
|
||||
// fix the error with at least two solutions
|
||||
// Fix the error with at least two solutions
|
||||
fn main() {
|
||||
let s: Box<str> = "hello, world".into();
|
||||
let s: Box<str> = "hello, world".into();
|
||||
greetings(s)
|
||||
}
|
||||
|
||||
|
@ -37,7 +37,7 @@ fn greetings(s: &str) {
|
|||
3. 🌟
|
||||
```rust,editable
|
||||
|
||||
// fill the blank
|
||||
// Fill the blank
|
||||
fn main() {
|
||||
let mut s = __;
|
||||
s.push_str("hello, world");
|
||||
|
@ -45,28 +45,28 @@ fn main() {
|
|||
|
||||
assert_eq!(s, "hello, world!");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
4. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fix all errors without adding newline
|
||||
// Fix all errors without adding newline
|
||||
fn main() {
|
||||
let s = String::from("hello");
|
||||
let s = String::from("hello");
|
||||
s.push(',');
|
||||
s.push(" world");
|
||||
s += "!".to_string();
|
||||
|
||||
println!("{}", s)
|
||||
println!("{}", s);
|
||||
}
|
||||
```
|
||||
|
||||
5. 🌟🌟 `replace` can be used to replace substring
|
||||
```rust,editable
|
||||
|
||||
// fill the blank
|
||||
// Fill the blank
|
||||
fn main() {
|
||||
let s = String::from("I like dogs");
|
||||
// Allocate new memory and store the modified string there
|
||||
|
@ -74,17 +74,17 @@ fn main() {
|
|||
|
||||
assert_eq!(s1, "I like cats");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
More `String` methods can be found under [String](https://doc.rust-lang.org/std/string/struct.String.html) module.
|
||||
|
||||
6. 🌟🌟 You can only concat a `String` with `&str`, and `String`'s ownership can be moved to another variable
|
||||
6. 🌟🌟 You can only concat a `String` with `&str`, and `String`'s ownership can be moved to another variable.
|
||||
|
||||
```rust,editable
|
||||
|
||||
// fix errors without removing any line
|
||||
// Fix errors without removing any line
|
||||
fn main() {
|
||||
let s1 = String::from("hello,");
|
||||
let s2 = String::from("world!");
|
||||
|
@ -100,9 +100,9 @@ Opsite to the seldom using of `str`, `&str` and `String` are used everywhere!
|
|||
7. 🌟🌟 `&str` can be converted to `String` in two ways
|
||||
```rust,editable
|
||||
|
||||
// fix error with at lest two solutions
|
||||
// Fix error with at least two solutions
|
||||
fn main() {
|
||||
let s = "hello, world";
|
||||
let s = "hello, world";
|
||||
greetings(s)
|
||||
}
|
||||
|
||||
|
@ -115,25 +115,25 @@ fn greetings(s: String) {
|
|||
|
||||
```rust,editable
|
||||
|
||||
// use two approaches to fix the error and without adding a new line
|
||||
// Use two approaches to fix the error and without adding a new line
|
||||
fn main() {
|
||||
let s = "hello, world".to_string();
|
||||
let s = "hello, world".to_string();
|
||||
let s1: &str = s;
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
### string escapes
|
||||
### String escapes
|
||||
9. 🌟
|
||||
```rust,editable
|
||||
fn main() {
|
||||
// You can use escapes to write bytes by their hexadecimal values
|
||||
// fill the blank below to show "I'm writing Rust"
|
||||
// Fill the blank below to show "I'm writing Rust"
|
||||
let byte_escape = "I'm writing Ru\x73__!";
|
||||
println!("What are you doing\x3F (\\x3F means ?) {}", byte_escape);
|
||||
|
||||
// ...or Unicode code points.
|
||||
// ...Or Unicode code points.
|
||||
let unicode_codepoint = "\u{211D}";
|
||||
let character_name = "\"DOUBLE-STRUCK CAPITAL R\"";
|
||||
|
||||
|
@ -152,9 +152,9 @@ fn main() {
|
|||
|
||||
```rust,editable
|
||||
|
||||
/* Fill in the blank and fix the errors */
|
||||
fn main() {
|
||||
let raw_str = r"Escapes don't work here: \x3F \u{211D}";
|
||||
// modify below line to make it work
|
||||
assert_eq!(raw_str, "Escapes don't work here: ? ℝ");
|
||||
|
||||
// If you need quotes in a raw string, add a pair of #s
|
||||
|
@ -166,15 +166,14 @@ fn main() {
|
|||
let delimiter = r###"A string with "# in it. And even "##!"###;
|
||||
println!("{}", delimiter);
|
||||
|
||||
// fill the blank
|
||||
let long_delimiter = __;
|
||||
assert_eq!(long_delimiter, "Hello, \"##\"");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
### byte string
|
||||
### Byte string
|
||||
Want a string that's not UTF-8? (Remember, str and String must be valid UTF-8). Or maybe you want an array of bytes that's mostly text? Byte strings to the rescue!
|
||||
|
||||
**Example**:
|
||||
|
@ -190,8 +189,8 @@ fn main() {
|
|||
|
||||
// Byte strings can have byte escapes...
|
||||
let escaped = b"\x52\x75\x73\x74 as bytes";
|
||||
// ...but no unicode escapes
|
||||
// let escaped = b"\u{211D} is not allowed";
|
||||
// ...But no unicode escapes
|
||||
// let escaped = b"\u{211D} Is not allowed";
|
||||
println!("Some escaped bytes: {:?}", escaped);
|
||||
|
||||
|
||||
|
@ -208,7 +207,7 @@ fn main() {
|
|||
like with normal raw strings"#;
|
||||
|
||||
// Byte strings don't have to be UTF-8
|
||||
let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82\xbb"; // "ようこそ" in SHIFT-JIS
|
||||
let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82\xbb"; // "ようこそ" In SHIFT-JIS
|
||||
|
||||
// But then they can't always be converted to `str`
|
||||
match str::from_utf8(shift_jis) {
|
||||
|
@ -220,29 +219,29 @@ fn main() {
|
|||
|
||||
A more detailed listing of the ways to write string literals and escape characters is given in the ['Tokens' chapter](https://doc.rust-lang.org/reference/tokens.html) of the Rust Reference.
|
||||
|
||||
### string index
|
||||
### String index
|
||||
11. 🌟🌟🌟 You can't use index to access a char in a string, but you can use slice `&s1[start..end]`.
|
||||
|
||||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
let s1 = String::from("hi,中国");
|
||||
let h = s1[0]; //modify this line to fix the error, tips: `h` only takes 1 byte in UTF8 format
|
||||
let h = s1[0]; // Modify this line to fix the error, tips: `h` only takes 1 byte in UTF8 format
|
||||
assert_eq!(h, "h");
|
||||
|
||||
let h1 = &s1[3..5];//modify this line to fix the error, tips: `中` takes 3 bytes in UTF8 format
|
||||
let h1 = &s1[3..5]; // Modify this line to fix the error, tips: `中` takes 3 bytes in UTF8 format
|
||||
assert_eq!(h1, "中");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
### operate on UTF8 string
|
||||
### Operate on UTF8 string
|
||||
12. 🌟
|
||||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
// fill the blank to print each char in "你好,世界"
|
||||
// Fill the blank to print each char in "你好,世界"
|
||||
for c in "你好,世界".__ {
|
||||
println!("{}", c)
|
||||
}
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
# Struct
|
||||
|
||||
### There types of structs
|
||||
### The types of structs
|
||||
1. 🌟 We must specify concrete values for each of the fields in struct.
|
||||
```rust,editable
|
||||
|
||||
// fix the error
|
||||
// Fix the error
|
||||
struct Person {
|
||||
name: String,
|
||||
age: u8,
|
||||
|
@ -17,7 +17,7 @@ fn main() {
|
|||
age,
|
||||
};
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -27,35 +27,35 @@ fn main() {
|
|||
|
||||
struct Unit;
|
||||
trait SomeTrait {
|
||||
// ...Some behavours defines here
|
||||
// ...Some behaviors defined here.
|
||||
}
|
||||
|
||||
// We don't care the the fields are in Unit, but we care its behaviors.
|
||||
// We don't care about what fields are in the Unit, but we care about its behaviors.
|
||||
// So we use a struct with no fields and implement some behaviors for it
|
||||
impl SomeTrait for Unit { }
|
||||
fn main() {
|
||||
let u = Unit;
|
||||
do_something_with_unit(u);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
// fill the blank to make the code work
|
||||
// Fill the blank to make the code work
|
||||
fn do_something_with_unit(u: __) { }
|
||||
```
|
||||
|
||||
3. 🌟🌟🌟 Tuple struct looks similar to tuples, it has added meaning the struct name provides but has no named fields. It's useful when you want give the whole tuple a name, but don't care the fields's names.
|
||||
3. 🌟🌟🌟 Tuple struct looks similar to tuples, it has added meaning the struct name provides but has no named fields. It's useful when you want to give the whole tuple a name, but don't care about the fields's names.
|
||||
|
||||
```rust,editable
|
||||
|
||||
// fix the error and fill the blanks
|
||||
// Fix the error and fill the blanks
|
||||
struct Color(i32, i32, i32);
|
||||
struct Point(i32, i32, i32);
|
||||
fn main() {
|
||||
let v = Point(__, __, __);
|
||||
check_color(v);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn check_color(p: Color) {
|
||||
|
@ -66,13 +66,13 @@ fn check_color(p: Color) {
|
|||
}
|
||||
```
|
||||
|
||||
### Operate on structs
|
||||
### Operating on structs
|
||||
|
||||
4. 🌟 You can make a whole struct mutable when instantiate it, but Rust doesn't allow us to mark only certain fields as mutable.
|
||||
4. 🌟 You can make a whole struct mutable when instantiating it, but Rust doesn't allow us to mark only certain fields as mutable.
|
||||
|
||||
```rust,editable
|
||||
|
||||
// fill the blank and fix the error without adding/removing new line
|
||||
// Fill the blank and fix the error without adding/removing new line
|
||||
struct Person {
|
||||
name: String,
|
||||
age: u8,
|
||||
|
@ -84,26 +84,26 @@ fn main() {
|
|||
age,
|
||||
};
|
||||
|
||||
// how can you believe sunface is only 18?
|
||||
// How can you believe sunface is only 18?
|
||||
p.age = 30;
|
||||
|
||||
// fill the lank
|
||||
// Fill the blank
|
||||
__ = String::from("sunfei");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
5. 🌟 Using *field init shorthand syntax* to reduct repetitions.
|
||||
5. 🌟 Using *field init shorthand syntax* to reduce repetitions.
|
||||
```rust,editable
|
||||
|
||||
// fill the blank
|
||||
// Fill the blank
|
||||
struct Person {
|
||||
name: String,
|
||||
age: u8,
|
||||
}
|
||||
fn main() {
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn build_person(name: String, age: u8) -> Person {
|
||||
|
@ -117,7 +117,7 @@ fn build_person(name: String, age: u8) -> Person {
|
|||
6. 🌟 You can create instance from other instance with *struct update syntax*
|
||||
```rust,editable
|
||||
|
||||
// fill the blank to make the code work
|
||||
// Fill the blank to make the code work
|
||||
struct User {
|
||||
active: bool,
|
||||
username: String,
|
||||
|
@ -134,7 +134,7 @@ fn main() {
|
|||
|
||||
let u2 = set_email(u1);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn set_email(u: User) -> User {
|
||||
|
@ -146,11 +146,11 @@ fn set_email(u: User) -> User {
|
|||
```
|
||||
|
||||
### Print the structs
|
||||
7. 🌟🌟 We can use `#[derive(Debug)]` to [make a struct prinable](https://doc.rust-lang.org/book/ch05-02-example-structs.html?highlight=%23%5Bderive(Debug)%5D#adding-useful-functionality-with-derived-traits).
|
||||
7. 🌟🌟 We can use `#[derive(Debug)]` to [make a struct printable](https://doc.rust-lang.org/book/ch05-02-example-structs.html?highlight=%23%5Bderive(Debug)%5D#adding-useful-functionality-with-derived-traits).
|
||||
|
||||
```rust,editable
|
||||
|
||||
// fill the blanks to make the code work
|
||||
// Fill the blanks to make the code work
|
||||
#[__]
|
||||
struct Rectangle {
|
||||
width: u32,
|
||||
|
@ -160,13 +160,13 @@ struct Rectangle {
|
|||
fn main() {
|
||||
let scale = 2;
|
||||
let rect1 = Rectangle {
|
||||
width: dbg!(30 * scale), // print debug info to stderr and assign the value of `30 * scale` to `width`
|
||||
width: dbg!(30 * scale), // Print debug info to stderr and assign the value of `30 * scale` to `width`
|
||||
height: 50,
|
||||
};
|
||||
|
||||
dbg!(&rect1); // print debug info to stderr
|
||||
dbg!(&rect1); // Print debug info to stderr
|
||||
|
||||
println!(__, rect1); // print debug info to stdout
|
||||
println!(__, rect1); // Print debug info to stdout
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -209,7 +209,7 @@ fn main() {
|
|||
8. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fix errors to make it work
|
||||
// Fix errors to make it work
|
||||
#[derive(Debug)]
|
||||
struct File {
|
||||
name: String,
|
||||
|
|
|
@ -6,29 +6,29 @@ fn main() {
|
|||
let _t0: (u8,i16) = (0, -1);
|
||||
// Tuples can be tuple's members
|
||||
let _t1: (u8, (i16, u32)) = (0, (-1, 1));
|
||||
// fill the blanks to make the code work
|
||||
// Fill the blanks to make the code work
|
||||
let t: (u8, __, i64, __, __) = (1u8, 2u16, 3i64, "hello", String::from(", world"));
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
2. 🌟 Members can be extracted from the tuple using indexing.
|
||||
```rust,editable
|
||||
|
||||
// make it works
|
||||
// Make it work
|
||||
fn main() {
|
||||
let t = ("i", "am", "sunface");
|
||||
assert_eq!(t.1, "sunface");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
3. 🌟 Long tuples cannot be printed
|
||||
```rust,editable
|
||||
|
||||
// fix the error
|
||||
// Fix the error
|
||||
fn main() {
|
||||
let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
|
||||
println!("too long tuple: {:?}", too_long_tuple);
|
||||
|
@ -41,14 +41,14 @@ fn main() {
|
|||
fn main() {
|
||||
let tup = (1, 6.4, "hello");
|
||||
|
||||
// fill the blank to make the code work
|
||||
// Fill the blank to make the code work
|
||||
let __ = tup;
|
||||
|
||||
assert_eq!(x, 1);
|
||||
assert_eq!(y, "hello");
|
||||
assert_eq!(z, 6.4);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -57,14 +57,14 @@ fn main() {
|
|||
fn main() {
|
||||
let (x, y, z);
|
||||
|
||||
// fill the blank
|
||||
// Fill the blank
|
||||
__ = (1, 2, 3);
|
||||
|
||||
assert_eq!(x, 3);
|
||||
assert_eq!(y, 1);
|
||||
assert_eq!(z, 2);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -72,13 +72,13 @@ fn main() {
|
|||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
// fill the blank, need a few computations here.
|
||||
// Fill the blank, need a few computations here.
|
||||
let (x, y) = sum_multiply(__);
|
||||
|
||||
assert_eq!(x, 5);
|
||||
assert_eq!(y, 6);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn sum_multiply(nums: (i32, i32)) -> (i32, i32) {
|
||||
|
|
|
@ -30,10 +30,15 @@ Tutorial [`https://www.philippflenker.com/hecto/`](https://www.philippflenker.co
|
|||
|
||||
[This blog series](https://os.phil-opp.com) creates a small operating system in the Rust programming language. Each post is a small tutorial and includes all needed code, so you can follow along if you like. The source code is also available in the corresponding [Github repository](https://github.com/phil-opp/blog_os).
|
||||
|
||||
|
||||
### 7. CodeCrafters.io: Build your own Git, Docker, SQLite, or Redis
|
||||
|
||||
On [CodeCrafters](https://codecrafters.io/for/rust), you can recreate your favorite developer tools from scratch. It's a hands-on, minimally-guided approach to master Rust, while appreciating the internals and documentation of popular technology that we use every day.
|
||||
|
||||
### 8. mini-redis
|
||||
[mini-redis](https://github.com/tokio-rs/mini-redis) is an incomplete Redis client and server implementation using tokio, it has decent code base and detail explanations, very suitable for learning Rust and asynchronous programming.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
# Flow control
|
||||
|
||||
### if/else
|
||||
### If/else
|
||||
1. 🌟
|
||||
```rust,editable
|
||||
|
||||
// fill in the blanks
|
||||
// Fill in the blanks
|
||||
fn main() {
|
||||
let n = 5;
|
||||
|
||||
|
@ -18,10 +18,10 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
2. 🌟🌟 `if/else` expression can be used in assignments.
|
||||
2. 🌟🌟 `If/else` expression can be used in assignments.
|
||||
```rust,editable
|
||||
|
||||
// fix the errors
|
||||
// Fix the errors
|
||||
fn main() {
|
||||
let n = 5;
|
||||
|
||||
|
@ -40,7 +40,7 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
### for
|
||||
### For
|
||||
3. 🌟 The `for in` construct can be used to iterate through an Iterator, e.g a range `a..b`.
|
||||
|
||||
```rust,editable
|
||||
|
@ -52,7 +52,7 @@ fn main() {
|
|||
}
|
||||
}
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -60,19 +60,19 @@ fn main() {
|
|||
4. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fix the errors without adding or removing lines
|
||||
// Fix the errors without adding or removing lines
|
||||
fn main() {
|
||||
let names = [String::from("liming"),String::from("hanmeimei")];
|
||||
for name in names {
|
||||
// do something with name...
|
||||
// Do something with name...
|
||||
}
|
||||
|
||||
println!("{:?}", names);
|
||||
|
||||
let numbers = [1, 2, 3];
|
||||
// the elements in numbers are Copy,so there is no move here
|
||||
// The elements in numbers are Copy,so there is no move here
|
||||
for n in numbers {
|
||||
// do something with name...
|
||||
// Do something with name...
|
||||
}
|
||||
|
||||
println!("{:?}", numbers);
|
||||
|
@ -84,19 +84,19 @@ fn main() {
|
|||
fn main() {
|
||||
let a = [4, 3, 2, 1];
|
||||
|
||||
// iterate the indexing and value in 'a'
|
||||
// Iterate the indexing and value in 'a'
|
||||
for (i,v) in a.__ {
|
||||
println!("The {}th element is {}",i+1,v);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### while
|
||||
### While
|
||||
6. 🌟🌟 The `while` keyword can be used to run a loop when a condition is true.
|
||||
|
||||
```rust,editable
|
||||
|
||||
// fill in the blanks to make the last println! work !
|
||||
// Fill in the blanks to make the last println! work !
|
||||
fn main() {
|
||||
// A counter variable
|
||||
let mut n = 1;
|
||||
|
@ -117,15 +117,15 @@ fn main() {
|
|||
__;
|
||||
}
|
||||
|
||||
println!("n reached {}, soloop is over",n);
|
||||
println!("n reached {}, so loop is over",n);
|
||||
}
|
||||
```
|
||||
|
||||
### continue and break
|
||||
7. 🌟 use `break` to break the loop.
|
||||
### Continue and break
|
||||
7. 🌟 Use `break` to break the loop.
|
||||
```rust,editable
|
||||
|
||||
// fill in the blank
|
||||
// Fill in the blank
|
||||
fn main() {
|
||||
let mut n = 0;
|
||||
for i in 0..=100 {
|
||||
|
@ -137,14 +137,14 @@ fn main() {
|
|||
|
||||
assert_eq!(n, 66);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
8. 🌟🌟 `continue` will skip over the remaining code in current iteration and go to the next iteration.
|
||||
```rust,editable
|
||||
|
||||
// fill in the blanks
|
||||
// Fill in the blanks
|
||||
fn main() {
|
||||
let mut n = 0;
|
||||
for i in 0..=100 {
|
||||
|
@ -158,17 +158,17 @@ fn main() {
|
|||
|
||||
assert_eq!(n, 66);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
### loop
|
||||
### Loop
|
||||
|
||||
9. 🌟🌟 loop is usually used together with `break` or `continue`.
|
||||
9. 🌟🌟 Loop is usually used together with `break` or `continue`.
|
||||
|
||||
```rust,editable
|
||||
|
||||
// fill in the blanks
|
||||
// Fill in the blanks
|
||||
fn main() {
|
||||
let mut count = 0u32;
|
||||
|
||||
|
@ -196,14 +196,14 @@ fn main() {
|
|||
|
||||
assert_eq!(count, 5);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
10. 🌟🌟 loop is an expression, so we can use it with `break` to return a value
|
||||
10. 🌟🌟 Loop is an expression, so we can use it with `break` to return a value
|
||||
```rust,editable
|
||||
|
||||
// fill in the blank
|
||||
// Fill in the blank
|
||||
fn main() {
|
||||
let mut counter = 0;
|
||||
|
||||
|
@ -217,7 +217,7 @@ fn main() {
|
|||
|
||||
assert_eq!(result, 20);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -225,14 +225,14 @@ fn main() {
|
|||
|
||||
```rust,editable
|
||||
|
||||
// fill in the blank
|
||||
// Fill in the blank
|
||||
fn main() {
|
||||
let mut count = 0;
|
||||
'outer: loop {
|
||||
'inner1: loop {
|
||||
if count >= 20 {
|
||||
// This would break only the inner1 loop
|
||||
break 'inner1; // `break` is also ok
|
||||
break 'inner1; // `break` is also works.
|
||||
}
|
||||
count += 2;
|
||||
}
|
||||
|
@ -252,7 +252,7 @@ fn main() {
|
|||
|
||||
assert!(count == __);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -173,7 +173,7 @@ fn main() {
|
|||
fn main() {
|
||||
let mut s = String::new();
|
||||
|
||||
let update_string = |str| s.push_str(str);
|
||||
let update_string = |str| s.push_str(str);
|
||||
|
||||
exec(update_string);
|
||||
|
||||
|
@ -260,7 +260,7 @@ move closures may still implement `Fn` or `FnMut`, even though they capture vari
|
|||
fn main() {
|
||||
let s = String::new();
|
||||
|
||||
let update_string = move || println!("{}",s);
|
||||
let update_string = move || println!("{}",s);
|
||||
|
||||
exec(update_string);
|
||||
}
|
||||
|
@ -275,7 +275,7 @@ The following code also has no error:
|
|||
fn main() {
|
||||
let s = String::new();
|
||||
|
||||
let update_string = move || println!("{}",s);
|
||||
let update_string = move || println!("{}",s);
|
||||
|
||||
exec(update_string);
|
||||
}
|
||||
|
|
|
@ -9,7 +9,7 @@ pub trait CacheableItem: Clone + Default + fmt::Debug + Decodable + Encodable {
|
|||
}
|
||||
```
|
||||
|
||||
Using of `Address` is much more clearable and convenient than `AsRef<[u8]> + Clone + fmt::Debug + Eq + Hash`.
|
||||
Using of `Address` is much more clearer and convenient than `AsRef<[u8]> + Clone + fmt::Debug + Eq + Hash`.
|
||||
|
||||
1. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
@ -89,7 +89,7 @@ fn main() {
|
|||
assert_eq!(Point { x: 2, y: 3 } - Point { x: 1, y: 0 },
|
||||
Point { x: 1, y: 3 });
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -110,7 +110,7 @@ trait AgeWidget {
|
|||
fn get(&self) -> u8;
|
||||
}
|
||||
|
||||
// A form with both a UsernameWidget and an AgeWidget
|
||||
// A form with both a UsernameWidget and an AgeWidget.
|
||||
struct Form {
|
||||
username: String,
|
||||
age: u8,
|
||||
|
@ -141,10 +141,10 @@ fn main() {
|
|||
|
||||
let username = UsernameWidget::get(&form);
|
||||
assert_eq!("rustacean".to_owned(), username);
|
||||
let age = AgeWidget::get(&form); // you can also use `<Form as AgeWidget>::get`
|
||||
let age = AgeWidget::get(&form); // You can also use `<Form as AgeWidget>::get`
|
||||
assert_eq!(28, age);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -187,7 +187,7 @@ fn main() {
|
|||
|
||||
assert_eq!(__, "*waving arms furiously*");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -253,7 +253,7 @@ fn main() {
|
|||
## Orphan Rules
|
||||
We can’t implement external traits on external types. For example, we can’t implement the `Display` trait on `Vec<T>` within our own crate, because `Display` and `Vec<T>` are defined in the standard library and aren’t local to our crate.
|
||||
|
||||
This restriction is often called as the orphan rule, so named because the parent type is not present. This rule ensures that other people’s code can’t break your code and vice versa.
|
||||
This restriction is often called the orphan rule, so named because the parent type is not present. This rule ensures that other people’s code can’t break your code and vice versa.
|
||||
|
||||
It’s possible to get around this restriction using the newtype pattern, which involves creating a new type in a tuple struct.
|
||||
|
||||
|
|
|
@ -25,15 +25,15 @@ impl<T: Debug, const N: usize> Debug for ArrayPair<T, N> {
|
|||
fn foo<const N: usize>() {}
|
||||
|
||||
fn bar<T, const M: usize>() {
|
||||
foo::<M>(); // ok: `M` is a const parameter
|
||||
foo::<2021>(); // ok: `2021` is a literal
|
||||
foo::<{20 * 100 + 20 * 10 + 1}>(); // ok: const expression contains no generic parameters
|
||||
foo::<M>(); // Okay: `M` is a const parameter
|
||||
foo::<2021>(); // Okay: `2021` is a literal
|
||||
foo::<{20 * 100 + 20 * 10 + 1}>(); // Okay: const expression contains no generic parameters
|
||||
|
||||
foo::<{ M + 1 }>(); // error: const expression contains the generic parameter `M`
|
||||
foo::<{ std::mem::size_of::<T>() }>(); // error: const expression contains the generic parameter `T`
|
||||
foo::<{ M + 1 }>(); // Error: const expression contains the generic parameter `M`
|
||||
foo::<{ std::mem::size_of::<T>() }>(); // Error: const expression contains the generic parameter `T`
|
||||
|
||||
let _: [u8; M]; // ok: `M` is a const parameter
|
||||
let _: [u8; std::mem::size_of::<T>()]; // error: const expression contains the generic parameter `T`
|
||||
let _: [u8; M]; // Okay: `M` is a const parameter
|
||||
let _: [u8; std::mem::size_of::<T>()]; // Error: const expression contains the generic parameter `T`
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
|
@ -89,14 +89,14 @@ fn main() {
|
|||
}
|
||||
];
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
2. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fill in the blanks to make it work
|
||||
// Fill in the blanks to make it work.
|
||||
fn print_array<__>(__) {
|
||||
println!("{:?}", arr);
|
||||
}
|
||||
|
@ -109,7 +109,7 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
3. 🌟🌟🌟 Sometimes we want to limit the size of an variable, e.g when using in embedding evironments, then `const expressions` will fit your need.
|
||||
3. 🌟🌟🌟 Sometimes we want to limit the size of a variable, e.g when using in embedding environments, then `const expressions` will fit your needs.
|
||||
|
||||
```rust,editable
|
||||
#![allow(incomplete_features)]
|
||||
|
@ -122,15 +122,15 @@ where
|
|||
//...
|
||||
}
|
||||
|
||||
// fix the errors in main
|
||||
// Fix the errors in main.
|
||||
fn main() {
|
||||
check_size([0u8; 767]);
|
||||
check_size([0i32; 191]);
|
||||
check_size(["hello你好"; __]); // size of &str ?
|
||||
check_size(["hello你好".to_string(); __]); // size of String?
|
||||
check_size(['中'; __]); // size of char ?
|
||||
check_size(["hello你好"; __]); // Size of &str ?
|
||||
check_size([(); __].map(|_| "hello你好".to_string())); // Size of String?
|
||||
check_size(['中'; __]); // Size of char ?
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
1. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fill in the blanks to make it work
|
||||
// Fill in the blanks to make it work
|
||||
struct A; // Concrete type `A`.
|
||||
struct S(A); // Concrete type `S`.
|
||||
struct SGen<T>(T); // Generic type `SGen`.
|
||||
|
@ -29,14 +29,14 @@ fn main() {
|
|||
// Implicitly specified type parameter `char` to `generic()`.
|
||||
generic(__);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
2. 🌟🌟 A function call with explicitly specified type parameters looks like: `fun::<A, B, ...>()`.
|
||||
```rust,editable
|
||||
|
||||
// implement the generic function below
|
||||
// Implement the generic function below.
|
||||
fn sum
|
||||
|
||||
fn main() {
|
||||
|
@ -44,7 +44,7 @@ fn main() {
|
|||
assert_eq!(50, sum(20, 30));
|
||||
assert_eq!(2.46, sum(1.23, 1.23));
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -54,38 +54,38 @@ fn main() {
|
|||
3. 🌟
|
||||
```rust,editable
|
||||
|
||||
// implement struct Point to make it work
|
||||
// Implement struct Point to make it work.
|
||||
|
||||
|
||||
fn main() {
|
||||
let integer = Point { x: 5, y: 10 };
|
||||
let float = Point { x: 1.0, y: 4.0 };
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
4. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// modify this struct to make the code work
|
||||
// Modify this struct to make the code work
|
||||
struct Point<T> {
|
||||
x: T,
|
||||
y: T,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// DON'T modify here
|
||||
// DON'T modify this code.
|
||||
let p = Point{x: 5, y : "hello".to_string()};
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
5. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// add generic for Val to make the code work, DON'T modify the code in `main`
|
||||
// Add generic for Val to make the code work, DON'T modify the code in `main`.
|
||||
struct Val {
|
||||
val: f64,
|
||||
}
|
||||
|
@ -114,7 +114,7 @@ struct Point<T, U> {
|
|||
}
|
||||
|
||||
impl<T, U> Point<T, U> {
|
||||
// implement mixup to make it work, DON'T modify other code
|
||||
// Implement mixup to make it work, DON'T modify other code.
|
||||
fn mixup
|
||||
}
|
||||
|
||||
|
@ -127,14 +127,14 @@ fn main() {
|
|||
assert_eq!(p3.x, 5);
|
||||
assert_eq!(p3.y, '中');
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
7. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fix the errors to make the code work
|
||||
// Fix the errors to make the code work.
|
||||
struct Point<T> {
|
||||
x: T,
|
||||
y: T,
|
||||
|
@ -148,7 +148,7 @@ impl Point<f32> {
|
|||
|
||||
fn main() {
|
||||
let p = Point{x: 5, y: 10};
|
||||
println!("{}",p.distance_from_origin())
|
||||
println!("{}",p.distance_from_origin());
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ In [traits chapter](https://practice.rs/generics-traits/traits.html#returning-ty
|
|||
Also one limitation of arrays is that they can only store elements of one type, yeah, enum is a not bad solution when our items are a fixed set of types in compile time, but trait object are more flexible and powerful here.
|
||||
|
||||
## Returning Traits with dyn
|
||||
The Rust compiler needs to know how much space a function's return type requires. Because the different implementations of a trait probably will need different amounts of memoery, this means function need to return a concrete type or the same type when using `impl Trait`, or it can return a trait object with `dyn`.
|
||||
The Rust compiler needs to know how much space a function's return type requires. Because the different implementations of a trait probably will need different amounts of memory, this means function need to return a concrete type or the same type when using `impl Trait`, or it can return a trait object with `dyn`.
|
||||
|
||||
1. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
@ -39,26 +39,26 @@ impl Bird for Swan {
|
|||
}
|
||||
|
||||
fn main() {
|
||||
// FILL in the blank
|
||||
// FILL in the blank.
|
||||
let duck = __;
|
||||
duck.swim();
|
||||
|
||||
let bird = hatch_a_bird(2);
|
||||
// this bird has forgotten how to swim, so below line will cause an error
|
||||
// This bird has forgotten how to swim, so below line will cause an error.
|
||||
// bird.swim();
|
||||
// but it can quak
|
||||
// But it can quak.
|
||||
assert_eq!(bird.quack(), "duck duck");
|
||||
|
||||
let bird = hatch_a_bird(1);
|
||||
// this bird has forgotten how to fly, so below line will cause an error
|
||||
// This bird has forgotten how to fly, so below line will cause an error.
|
||||
// bird.fly();
|
||||
// but it can quak too
|
||||
// But it can quak too.
|
||||
assert_eq!(bird.quack(), "swan swan");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
// IMPLEMENT this function
|
||||
// IMPLEMENT this function.
|
||||
fn hatch_a_bird...
|
||||
|
||||
```
|
||||
|
@ -95,13 +95,13 @@ impl Bird for Swan {
|
|||
}
|
||||
|
||||
fn main() {
|
||||
// FILL in the blank to make the code work
|
||||
// FILL in the blank to make the code work.
|
||||
let birds __;
|
||||
|
||||
for bird in birds {
|
||||
bird.quack();
|
||||
// when duck and swan turns into Bird, they all forgot how to fly, only remeber how to quack
|
||||
// so, the below code will cause an error
|
||||
// When duck and swan turn into Birds, they all forgot how to fly, only remember how to quack.
|
||||
// So, the code below will cause an error.
|
||||
// bird.fly();
|
||||
}
|
||||
}
|
||||
|
@ -113,7 +113,7 @@ fn main() {
|
|||
3. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// FILL in the blanks
|
||||
// FILL in the blanks.
|
||||
trait Draw {
|
||||
fn draw(&self) -> String;
|
||||
}
|
||||
|
@ -134,13 +134,13 @@ fn main() {
|
|||
let x = 1.1f64;
|
||||
let y = 8u8;
|
||||
|
||||
// draw x
|
||||
// Draw x.
|
||||
draw_with_box(__);
|
||||
|
||||
// draw y
|
||||
// Draw y.
|
||||
draw_with_ref(&y);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn draw_with_box(x: Box<dyn Draw>) {
|
||||
|
@ -153,11 +153,11 @@ fn draw_with_ref(x: __) {
|
|||
```
|
||||
|
||||
## Static and Dynamic dispatch
|
||||
when we use trait bounds on generics: the compiler generates nongeneric implementations of functions and methods for each concrete type that we use in place of a generic type parameter. The code that results from monomorphization is doing static dispatch, which is when the compiler knows what method you’re calling at compile time.
|
||||
When we use trait bounds on generics, the compiler generates nongeneric implementations of functions and methods for each concrete type that we use in place of a generic type parameter. The code that results from monomorphization is doing static dispatch, which is when the compiler knows what method you’re calling at compile time.
|
||||
|
||||
When we use trait objects, Rust must use dynamic dispatch. The compiler doesn’t know all the types that might be used with the code that is using trait objects, so it doesn’t know which method implemented on which type to call. Instead, at runtime, Rust uses the pointers inside the trait object to know which method to call. There is a runtime cost when this lookup happens that doesn’t occur with static dispatch. Dynamic dispatch also prevents the compiler from choosing to inline a method’s code, which in turn prevents some optimizations.
|
||||
|
||||
However, we did get extra flexibility when using dynamic dispatch.
|
||||
However, we do get extra flexibility when using dynamic dispatch.
|
||||
|
||||
4. 🌟🌟
|
||||
```rust,editable
|
||||
|
@ -174,10 +174,10 @@ impl Foo for String {
|
|||
fn method(&self) -> String { format!("string: {}", *self) }
|
||||
}
|
||||
|
||||
// IMPLEMENT below with generics
|
||||
// IMPLEMENT below with generics.
|
||||
fn static_dispatch...
|
||||
|
||||
// implement below with trait objects
|
||||
// Implement below with trait objects.
|
||||
fn dynamic_dispatch...
|
||||
|
||||
fn main() {
|
||||
|
@ -187,7 +187,7 @@ fn main() {
|
|||
static_dispatch(x);
|
||||
dynamic_dispatch(&y);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -200,8 +200,8 @@ You can only make object-safe traits into trait objects. A trait is object safe
|
|||
5. 🌟🌟🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// Use at least two approaches to make it work
|
||||
// DON'T add/remove any code line
|
||||
// Use at least two approaches to make it work.
|
||||
// DON'T add/remove any code line.
|
||||
trait MyTrait {
|
||||
fn f(&self) -> Self;
|
||||
}
|
||||
|
@ -222,7 +222,7 @@ fn main() {
|
|||
my_function(Box::new(13_u32));
|
||||
my_function(Box::new(String::from("abc")));
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -81,8 +81,8 @@ fn main() {
|
|||
1. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fill in the two impl blocks to make the code work
|
||||
// DON'T modify the code in `main`
|
||||
// Fill in the two impl blocks to make the code work.
|
||||
// DON'T modify the code in `main`.
|
||||
trait Hello {
|
||||
fn say_hi(&self) -> String {
|
||||
String::from("hi")
|
||||
|
@ -107,7 +107,7 @@ fn main() {
|
|||
assert_eq!(t.say_hi(), "Hi, I'm your new teacher");
|
||||
assert_eq!(t.say_something(), "I'm not a bad teacher");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -135,7 +135,7 @@ impl Inches {
|
|||
}
|
||||
|
||||
// ADD some attributes to make the code work!
|
||||
// DON'T modify other codes!
|
||||
// DON'T modify other code!
|
||||
struct Seconds(i32);
|
||||
|
||||
fn main() {
|
||||
|
@ -171,23 +171,23 @@ In Rust, many of the operators can be overloaded via traits. That is, some opera
|
|||
|
||||
use std::ops;
|
||||
|
||||
// implement fn multiply to make the code work
|
||||
// As mentiond above, `+` needs `T` to implement `std::ops::Add` Trait
|
||||
// so, what about `*` ? You can find the answer here: https://doc.rust-lang.org/core/ops/
|
||||
// Implement fn multiply to make the code work.
|
||||
// As mentiond above, `+` needs `T` to implement `std::ops::Add` Trait.
|
||||
// So, what about `*`? You can find the answer here: https://doc.rust-lang.org/core/ops/
|
||||
fn multipl
|
||||
|
||||
fn main() {
|
||||
assert_eq!(6, multiply(2u8, 3u8));
|
||||
assert_eq!(5.0, multiply(1.0, 5.0));
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
4. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fix the errors, DON'T modify the code in `main`
|
||||
// Fix the errors, DON'T modify the code in `main`.
|
||||
use std::ops;
|
||||
|
||||
struct Foo;
|
||||
|
@ -217,12 +217,12 @@ impl ops::Sub<Foo> for Bar {
|
|||
}
|
||||
|
||||
fn main() {
|
||||
// DON'T modify the below code
|
||||
// you need to derive some trait for FooBar to make it comparable
|
||||
// DON'T modify the code below.
|
||||
// You need to derive some trait for FooBar to make it comparable.
|
||||
assert_eq!(Foo + Bar, FooBar);
|
||||
assert_eq!(Foo - Bar, BarFoo);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -232,8 +232,8 @@ Instead of a concrete type for the item parameter, we specify the impl keyword a
|
|||
5. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// implement `fn summary` to make the code work
|
||||
// fix the errors without removing any code line
|
||||
// Implement `fn summary` to make the code work.
|
||||
// Fix the errors without removing any code line
|
||||
trait Summary {
|
||||
fn summarize(&self) -> String;
|
||||
}
|
||||
|
@ -281,14 +281,14 @@ fn main() {
|
|||
println!("{:?}", weibo);
|
||||
}
|
||||
|
||||
// implement `fn summary` below
|
||||
// Implement `fn summary` below.
|
||||
|
||||
```
|
||||
|
||||
### Returning Types that Implement Traits
|
||||
We can also use the impl Trait syntax in the return position to return a value of some type that implements a trait.
|
||||
|
||||
However, you can only use impl Trait if you’re returning a single type, using Trait Objects instead when you really need to return serveral types.
|
||||
However, you can only use impl Trait if you’re returning a single type, use Trait Objects instead when you really need to return several types.
|
||||
|
||||
6. 🌟🌟
|
||||
```rust,editable
|
||||
|
@ -313,7 +313,7 @@ impl Animal for Cow {
|
|||
}
|
||||
|
||||
// Returns some struct that implements Animal, but we don't know which one at compile time.
|
||||
// FIX the erros here, you can make a fake random, or you can use trait object
|
||||
// FIX the errors here, you can make a fake random, or you can use trait object.
|
||||
fn random_animal(random_number: f64) -> impl Animal {
|
||||
if random_number < 0.5 {
|
||||
Sheep {}
|
||||
|
@ -340,7 +340,7 @@ fn main() {
|
|||
assert_eq!(sum(1, 2), 3);
|
||||
}
|
||||
|
||||
// implement `fn sum` with trait bound in two ways
|
||||
// Implement `fn sum` with trait bound in two ways.
|
||||
fn sum<T>(x: T, y: T) -> T {
|
||||
x + y
|
||||
}
|
||||
|
@ -348,7 +348,7 @@ fn sum<T>(x: T, y: T) -> T {
|
|||
8. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// FIX the errors
|
||||
// FIX the errors.
|
||||
struct Pair<T> {
|
||||
x: T,
|
||||
y: T,
|
||||
|
@ -388,10 +388,10 @@ fn main() {
|
|||
9. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fill in the blanks to make it work
|
||||
// Fill in the blanks to make it work
|
||||
fn example1() {
|
||||
// `T: Trait` is the commonly used way
|
||||
// `T: Fn(u32) -> u32` specifies that we can only pass a closure to `T`
|
||||
// `T: Trait` is the commonly used way.
|
||||
// `T: Fn(u32) -> u32` specifies that we can only pass a closure to `T`.
|
||||
struct Cacher<T: Fn(u32) -> u32> {
|
||||
calculation: T,
|
||||
value: Option<u32>,
|
||||
|
@ -424,7 +424,7 @@ fn example1() {
|
|||
|
||||
|
||||
fn example2() {
|
||||
// We can also use `where` to constrain `T`
|
||||
// We can also use `where` to construct `T`
|
||||
struct Cacher<T>
|
||||
where T: Fn(u32) -> u32,
|
||||
{
|
||||
|
@ -465,7 +465,7 @@ fn main() {
|
|||
example1();
|
||||
example2();
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# Associated function & Method
|
||||
# Associated functions & Methods
|
||||
|
||||
## Examples
|
||||
```rust,editable
|
||||
|
@ -7,7 +7,7 @@ struct Point {
|
|||
y: f64,
|
||||
}
|
||||
|
||||
// Implementation block, all `Point` associated functions & methods go in here
|
||||
// Implementation block, all `Point` associated functions & methods go in here.
|
||||
impl Point {
|
||||
// This is an "associated function" because this function is associated with
|
||||
// a particular type, that is, Point.
|
||||
|
@ -30,11 +30,11 @@ struct Rectangle {
|
|||
}
|
||||
|
||||
impl Rectangle {
|
||||
// This is a method
|
||||
// This is a method.
|
||||
// `&self` is sugar for `self: &Self`, where `Self` is the type of the
|
||||
// caller object. In this case `Self` = `Rectangle`
|
||||
fn area(&self) -> f64 {
|
||||
// `self` gives access to the struct fields via the dot operator
|
||||
// `self` gives access to the struct fields via the dot operator.
|
||||
let Point { x: x1, y: y1 } = self.p1;
|
||||
let Point { x: x2, y: y2 } = self.p2;
|
||||
|
||||
|
@ -61,7 +61,7 @@ impl Rectangle {
|
|||
}
|
||||
}
|
||||
|
||||
// `Pair` owns resources: two heap allocated integers
|
||||
// `Pair` owns resources: two heap allocated integers.
|
||||
struct Pair(Box<i32>, Box<i32>);
|
||||
|
||||
impl Pair {
|
||||
|
@ -73,7 +73,7 @@ impl Pair {
|
|||
|
||||
println!("Destroying Pair({}, {})", first, second);
|
||||
|
||||
// `first` and `second` go out of scope and get freed
|
||||
// `first` and `second` go out of scope and get freed.
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -84,7 +84,7 @@ fn main() {
|
|||
p2: Point::new(3.0, 4.0),
|
||||
};
|
||||
|
||||
// Methods are called using the dot operator
|
||||
// Methods are called using the dot operator.
|
||||
// Note that the first argument `&self` is implicitly passed, i.e.
|
||||
// `rectangle.perimeter()` === `Rectangle::perimeter(&rectangle)`
|
||||
println!("Rectangle perimeter: {}", rectangle.perimeter());
|
||||
|
@ -96,7 +96,7 @@ fn main() {
|
|||
};
|
||||
|
||||
// Error! `rectangle` is immutable, but this method requires a mutable
|
||||
// object
|
||||
// object.
|
||||
//rectangle.translate(1.0, 0.0);
|
||||
// TODO ^ Try uncommenting this line
|
||||
|
||||
|
@ -116,7 +116,7 @@ fn main() {
|
|||
## Exercises
|
||||
|
||||
### Method
|
||||
1. 🌟🌟 Methods are similar to functions: declare with `fn`, have parameters and a return value. Unlike functions, methods are defined within the context of a struct (or an enum or a trait object), and their first parameter is always `self`, which represents the instance of the struct the method is being called on.
|
||||
1. 🌟🌟 Methods are similar to functions: Declare with `fn`, have parameters and a return value. Unlike functions, methods are defined within the context of a struct (or an enum or a trait object), and their first parameter is always `self`, which represents the instance of the struct the method is being called on.
|
||||
```rust,editable
|
||||
struct Rectangle {
|
||||
width: u32,
|
||||
|
@ -124,7 +124,7 @@ struct Rectangle {
|
|||
}
|
||||
|
||||
impl Rectangle {
|
||||
// complete the area method which return the area of a Rectangle
|
||||
// Complete the area method which return the area of a Rectangle.
|
||||
fn area
|
||||
}
|
||||
|
||||
|
@ -133,11 +133,11 @@ fn main() {
|
|||
|
||||
assert_eq!(rect1.area(), 1500);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
2. 🌟🌟 `self` will take the ownership of current struct instance, however, `&self` will only borrow a reference from the instance
|
||||
2. 🌟🌟 `self` will take the ownership of current struct instance, however, `&self` will only borrow a reference from the instance.
|
||||
|
||||
```rust,editable
|
||||
// Only fill in the blanks, DON'T remove any line!
|
||||
|
@ -155,9 +155,9 @@ fn main() {
|
|||
let light = TrafficLight{
|
||||
color: "red".to_owned(),
|
||||
};
|
||||
// Don't take the ownership of `light` here
|
||||
// Don't take the ownership of `light` here.
|
||||
light.show_state();
|
||||
// ..otherwise, there will be an error below
|
||||
// ... Otherwise, there will be an error below
|
||||
println!("{:?}", light);
|
||||
}
|
||||
```
|
||||
|
@ -168,23 +168,23 @@ struct TrafficLight {
|
|||
}
|
||||
|
||||
impl TrafficLight {
|
||||
// using `Self` to fill in the blank
|
||||
// Using `Self` to fill in the blank.
|
||||
pub fn show_state(__) {
|
||||
println!("the current state is {}", self.color);
|
||||
}
|
||||
|
||||
// fill in the blank, DON'T use any variants of `Self`
|
||||
pub fn change_state() {
|
||||
// Fill in the blank, DON'T use any variants of `Self`.
|
||||
pub fn change_state(__) {
|
||||
self.color = "green".to_string()
|
||||
}
|
||||
}
|
||||
fn main() {
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Associated function
|
||||
### Associated functions
|
||||
|
||||
4. 🌟🌟 All functions defined within an `impl` block are called associated functions because they’re associated with the type named after the `impl`. We can define associated functions that don’t have `self` as their first parameter (and thus are not methods) because they don’t need an instance of the type to work with.
|
||||
|
||||
|
@ -195,9 +195,9 @@ struct TrafficLight {
|
|||
}
|
||||
|
||||
impl TrafficLight {
|
||||
// 1. implement a assotiated function `new`,
|
||||
// 2. it will return a TrafficLight contains color "red"
|
||||
// 3. must use `Self`, DONT use `TrafficLight` in fn signatures or body
|
||||
// 1. Implement an assotiated function `new`,
|
||||
// 2. It will return a TrafficLight contains color "red"
|
||||
// 3. Must use `Self`, DONT use `TrafficLight` in fn signatures or body
|
||||
pub fn new()
|
||||
|
||||
pub fn get_state(&self) -> &str {
|
||||
|
@ -209,7 +209,7 @@ fn main() {
|
|||
let light = TrafficLight::new();
|
||||
assert_eq!(light.get_state(), "red");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -222,7 +222,7 @@ struct Rectangle {
|
|||
height: u32,
|
||||
}
|
||||
|
||||
// using multiple `impl` blocks to rewrite the code below
|
||||
// Using multiple `impl` blocks to rewrite the code below.
|
||||
impl Rectangle {
|
||||
fn area(&self) -> u32 {
|
||||
self.width * self.height
|
||||
|
@ -235,7 +235,7 @@ impl Rectangle {
|
|||
|
||||
|
||||
fn main() {
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -251,7 +251,7 @@ enum TrafficLightColor {
|
|||
Green,
|
||||
}
|
||||
|
||||
// implement TrafficLightColor with a method
|
||||
// Implement TrafficLightColor with a method.
|
||||
impl TrafficLightColor {
|
||||
|
||||
}
|
||||
|
|
|
@ -6,10 +6,10 @@
|
|||
|
||||
fn main() {
|
||||
let x = 5;
|
||||
// fill the blank
|
||||
// Fill the blank
|
||||
let p = __;
|
||||
|
||||
println!("the memory address of x is {:p}", p); // one possible output: 0x16fa3ac84
|
||||
println!("the memory address of x is {:p}", p); // One possible output: 0x16fa3ac84
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -20,23 +20,23 @@ fn main() {
|
|||
let x = 5;
|
||||
let y = &x;
|
||||
|
||||
// modify this line only
|
||||
// Modify this line only
|
||||
assert_eq!(5, y);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
3. 🌟
|
||||
```rust,editable
|
||||
|
||||
// fix error
|
||||
// Fix error
|
||||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
||||
borrow_object(s);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn borrow_object(s: &String) {}
|
||||
|
@ -45,13 +45,13 @@ fn borrow_object(s: &String) {}
|
|||
4. 🌟
|
||||
```rust,editable
|
||||
|
||||
// fix error
|
||||
// Fix error
|
||||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
||||
push_str(s);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn push_str(s: &mut String) {
|
||||
|
@ -65,16 +65,16 @@ fn push_str(s: &mut String) {
|
|||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
||||
// fill the blank to make it work
|
||||
// Fill the blank to make it work
|
||||
let p = __;
|
||||
|
||||
p.push_str("world");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
#### ref
|
||||
#### Ref
|
||||
`ref` can be used to take references to a value, similar to `&`.
|
||||
|
||||
6. 🌟🌟🌟
|
||||
|
@ -84,18 +84,18 @@ fn main() {
|
|||
let c = '中';
|
||||
|
||||
let r1 = &c;
|
||||
// fill the blank,dont change other code
|
||||
// Fill the blank,dont change other code
|
||||
let __ r2 = c;
|
||||
|
||||
assert_eq!(*r1, *r2);
|
||||
|
||||
// check the equality of the two address strings
|
||||
// Check the equality of the two address strings
|
||||
assert_eq!(get_addr(r1),get_addr(r2));
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
// get memory address string
|
||||
// Get memory address string
|
||||
fn get_addr(r: &char) -> String {
|
||||
format!("{:p}", r)
|
||||
}
|
||||
|
@ -105,8 +105,8 @@ fn get_addr(r: &char) -> String {
|
|||
7. 🌟
|
||||
```rust,editable
|
||||
|
||||
// remove something to make it work
|
||||
// don't remove a whole line !
|
||||
// Remove something to make it work
|
||||
// Don't remove a whole line !
|
||||
fn main() {
|
||||
let mut s = String::from("hello");
|
||||
|
||||
|
@ -115,21 +115,21 @@ fn main() {
|
|||
|
||||
println!("{}, {}", r1, r2);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
#### Mutablity
|
||||
8. 🌟 Error: Borrow a immutable object as mutable
|
||||
#### Mutability
|
||||
8. 🌟 Error: Borrow an immutable object as mutable
|
||||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
//fix error by modifying this line
|
||||
// Fix error by modifying this line
|
||||
let s = String::from("hello, ");
|
||||
|
||||
borrow_object(&mut s);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn borrow_object(s: &mut String) {}
|
||||
|
@ -138,7 +138,7 @@ fn borrow_object(s: &mut String) {}
|
|||
9. 🌟🌟 Ok: Borrow a mutable object as immutable
|
||||
```rust,editable
|
||||
|
||||
// this code has no errors!
|
||||
// This code has no errors!
|
||||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
||||
|
@ -146,7 +146,7 @@ fn main() {
|
|||
|
||||
s.push_str("world");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn borrow_object(s: &String) {}
|
||||
|
@ -156,7 +156,7 @@ fn borrow_object(s: &String) {}
|
|||
10. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// comment one line to make it work
|
||||
// Comment one line to make it work
|
||||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
||||
|
@ -178,8 +178,8 @@ fn main() {
|
|||
let r1 = &mut s;
|
||||
let r2 = &mut s;
|
||||
|
||||
// add one line below to make a compiler error: cannot borrow `s` as mutable more than once at a time
|
||||
// you can't use r1 and r2 at the same time
|
||||
// Add one line below to make a compiler error: cannot borrow `s` as mutable more than once at a time
|
||||
// You can't use r1 and r2 at the same time
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
// use as many approaches as you can to make it work
|
||||
// Use as many approaches as you can to make it work
|
||||
let x = String::from("hello, world");
|
||||
let y = x;
|
||||
println!("{},{}",x,y);
|
||||
|
@ -39,7 +39,7 @@ fn main() {
|
|||
// Only modify the code below!
|
||||
fn give_ownership() -> String {
|
||||
let s = String::from("hello, world");
|
||||
// convert String to Vec
|
||||
// Convert String to Vec
|
||||
let _s = s.into_bytes();
|
||||
s
|
||||
}
|
||||
|
@ -47,7 +47,7 @@ fn give_ownership() -> String {
|
|||
|
||||
4. 🌟🌟
|
||||
```rust,editable
|
||||
// fix the error without removing code line
|
||||
// Fix the error without removing code line
|
||||
fn main() {
|
||||
let s = String::from("hello, world");
|
||||
|
||||
|
@ -63,7 +63,7 @@ fn print_str(s: String) {
|
|||
|
||||
5. 🌟🌟
|
||||
```rust, editable
|
||||
// don't use clone ,use copy instead
|
||||
// Don't use clone ,use copy instead
|
||||
fn main() {
|
||||
let x = (1, 2, (), "hello".to_string());
|
||||
let y = x.clone();
|
||||
|
@ -80,12 +80,12 @@ Mutability can be changed when ownership is transferred.
|
|||
fn main() {
|
||||
let s = String::from("hello, ");
|
||||
|
||||
// modify this line only !
|
||||
// Modify this line only !
|
||||
let s1 = s;
|
||||
|
||||
s1.push_str("world");
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -95,13 +95,13 @@ fn main() {
|
|||
fn main() {
|
||||
let x = Box::new(5);
|
||||
|
||||
let ... // implement this line, dont change other lines!
|
||||
let ... // Implement this line, dont change other lines!
|
||||
|
||||
*y = 4;
|
||||
|
||||
assert_eq!(*x, 5);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -148,7 +148,7 @@ fn main() {
|
|||
|
||||
let _s = t.0;
|
||||
|
||||
// modify this line only, don't use `_s`
|
||||
// Modify this line only, don't use `_s`
|
||||
println!("{:?}", t);
|
||||
}
|
||||
```
|
||||
|
@ -159,7 +159,7 @@ fn main() {
|
|||
fn main() {
|
||||
let t = (String::from("hello"), String::from("world"));
|
||||
|
||||
// fill the blanks
|
||||
// Fill the blanks
|
||||
let (__, __) = __;
|
||||
|
||||
println!("{:?}, {:?}, {:?}", s1, s2, t); // -> "hello", "world", ("hello", "world")
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
# match, if let
|
||||
# Match, if let
|
||||
|
||||
### match
|
||||
### Match
|
||||
1. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fill the blanks
|
||||
// Fill the blanks
|
||||
enum Direction {
|
||||
East,
|
||||
West,
|
||||
|
@ -16,7 +16,7 @@ fn main() {
|
|||
let dire = Direction::South;
|
||||
match dire {
|
||||
Direction::East => println!("East"),
|
||||
__ => { // matching South or North here
|
||||
__ => { // Matching South or North here
|
||||
println!("South or North");
|
||||
},
|
||||
_ => println!(__),
|
||||
|
@ -24,13 +24,13 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
2. 🌟🌟 match is an expression, so we can use it in assignments
|
||||
2. 🌟🌟 Match is an expression, so we can use it in assignments.
|
||||
```rust,editable
|
||||
|
||||
fn main() {
|
||||
let boolean = true;
|
||||
|
||||
// fill the blank with an match expression:
|
||||
// Fill the blank with a match expression:
|
||||
//
|
||||
// boolean = true => binary = 1
|
||||
// boolean = false => binary = 0
|
||||
|
@ -38,14 +38,14 @@ fn main() {
|
|||
|
||||
assert_eq!(binary, 1);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
3. 🌟🌟 using match to get the data an enum variant holds
|
||||
3. 🌟🌟 Using match to get the data an enum variant holds.
|
||||
```rust,editable
|
||||
|
||||
// fill in the blanks
|
||||
// Fill in the blanks
|
||||
enum Message {
|
||||
Quit,
|
||||
Move { x: i32, y: i32 },
|
||||
|
@ -64,7 +64,7 @@ fn main() {
|
|||
show_message(msg)
|
||||
}
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
|
||||
fn show_message(msg: Message) {
|
||||
|
@ -83,7 +83,7 @@ fn show_message(msg: Message) {
|
|||
```
|
||||
|
||||
### matches!
|
||||
[`matches!`](https://doc.rust-lang.org/stable/core/macro.matches.html) looks like `match`, but can do something different
|
||||
[`matches!`](https://doc.rust-lang.org/stable/core/macro.matches.html) looks like `match`, but can do something different.
|
||||
|
||||
4. 🌟🌟
|
||||
```rust,editable
|
||||
|
@ -91,12 +91,12 @@ fn show_message(msg: Message) {
|
|||
fn main() {
|
||||
let alphabets = ['a', 'E', 'Z', '0', 'x', '9' , 'Y'];
|
||||
|
||||
// fill the blank with `matches!` to make the code work
|
||||
// Fill the blank with `matches!` to make the code work
|
||||
for ab in alphabets {
|
||||
assert!(__)
|
||||
}
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -113,19 +113,19 @@ fn main() {
|
|||
|
||||
let v = vec![MyEnum::Foo,MyEnum::Bar,MyEnum::Foo];
|
||||
for e in v {
|
||||
if e == MyEnum::Foo { // fix the error with changing only this line
|
||||
if e == MyEnum::Foo { // Fix the error by changing only this line
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(count, 2);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
### if let
|
||||
For some cases, when matching enums, `match` is too heavy, we can use `if let` instead.
|
||||
### If let
|
||||
For some cases, when matching enums, `match` is too heavy. We can use `if let` instead.
|
||||
|
||||
6. 🌟
|
||||
```rust,editable
|
||||
|
@ -133,12 +133,12 @@ For some cases, when matching enums, `match` is too heavy, we can use `if let` i
|
|||
fn main() {
|
||||
let o = Some(7);
|
||||
|
||||
// remove the whole `match` block, using `if let` instead
|
||||
// Remove the whole `match` block, using `if let` instead
|
||||
match o {
|
||||
Some(i) => {
|
||||
println!("This is a really long string and `{:?}`", i);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
|
@ -148,7 +148,7 @@ fn main() {
|
|||
7. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fill in the blank
|
||||
// Fill in the blank
|
||||
enum Foo {
|
||||
Bar(u8)
|
||||
}
|
||||
|
@ -159,7 +159,7 @@ fn main() {
|
|||
__ {
|
||||
println!("foobar holds the value: {}", i);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -176,7 +176,7 @@ enum Foo {
|
|||
fn main() {
|
||||
let a = Foo::Qux(10);
|
||||
|
||||
// remove the codes below, using `match` instead
|
||||
// Remove the codes below, using `match` instead
|
||||
if let Foo::Bar = a {
|
||||
println!("match foo::bar")
|
||||
} else if let Foo::Baz = a {
|
||||
|
@ -191,15 +191,15 @@ fn main() {
|
|||
9. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fix the errors in-place
|
||||
// Fix the errors in-place
|
||||
fn main() {
|
||||
let age = Some(30);
|
||||
if let Some(age) = age { // create a new variable with the same name as previous `age`
|
||||
if let Some(age) = age { // Create a new variable with the same name as previous `age`
|
||||
assert_eq!(age, Some(30));
|
||||
} // the new variable `age` goes out of scope here
|
||||
} // The new variable `age` goes out of scope here
|
||||
|
||||
match age {
|
||||
// match can also introduce a new shadowed variable
|
||||
// Match can also introduce a new shadowed variable
|
||||
Some(age) => println!("age is a new variable, it's value is {}",age),
|
||||
_ => ()
|
||||
}
|
||||
|
|
|
@ -1,16 +1,16 @@
|
|||
# Patterns
|
||||
|
||||
1. 🌟🌟 use `|` to match several values, use `..=` to match a inclusive range
|
||||
1. 🌟🌟 Use `|` to match several values, use `..=` to match an inclusive range.
|
||||
```rust,editable
|
||||
|
||||
fn main() {}
|
||||
fn match_number(n: i32) {
|
||||
match n {
|
||||
// match a single value
|
||||
// Match a single value
|
||||
1 => println!("One!"),
|
||||
// fill in the blank with `|`, DON'T use `..` ofr `..=`
|
||||
// Fill in the blank with `|`, DON'T use `..` or `..=`
|
||||
__ => println!("match 2 -> 5"),
|
||||
// match an inclusive range
|
||||
// Match an inclusive range
|
||||
6..=10 => {
|
||||
println!("match 6 -> 10")
|
||||
},
|
||||
|
@ -21,7 +21,7 @@ fn match_number(n: i32) {
|
|||
}
|
||||
```
|
||||
|
||||
2. 🌟🌟🌟 The `@` operator lets us create a variable that holds a value at the same time we are testing that value to see whether it matches a pattern.
|
||||
2. 🌟🌟🌟 The `@` operator lets us create a variable that holds a value, at the same time we are testing that value to see whether it matches a pattern.
|
||||
```rust,editable
|
||||
|
||||
struct Point {
|
||||
|
@ -30,12 +30,12 @@ struct Point {
|
|||
}
|
||||
|
||||
fn main() {
|
||||
// fill in the blank to let p match the second arm
|
||||
// Fill in the blank to let p match the second arm
|
||||
let p = Point { x: __, y: __ };
|
||||
|
||||
match p {
|
||||
Point { x, y: 0 } => println!("On the x axis at {}", x),
|
||||
// second arm
|
||||
// Second arm
|
||||
Point { x: 0..=5, y: y@ (10 | 20 | 30) } => println!("On the y axis at {}", y),
|
||||
Point { x, y } => println!("On neither axis: ({}, {})", x, y),
|
||||
}
|
||||
|
@ -46,7 +46,7 @@ fn main() {
|
|||
|
||||
```rust,editable
|
||||
|
||||
// fix the errors
|
||||
// Fix the errors
|
||||
enum Message {
|
||||
Hello { id: i32 },
|
||||
}
|
||||
|
@ -69,7 +69,7 @@ fn main() {
|
|||
4. 🌟🌟 A match guard is an additional if condition specified after the pattern in a match arm that must also match, along with the pattern matching, for that arm to be chosen.
|
||||
```rust,editable
|
||||
|
||||
// fill in the blank to make the code work, `split` MUST be used
|
||||
// Fill in the blank to make the code work, `split` MUST be used
|
||||
fn main() {
|
||||
let num = Some(4);
|
||||
let split = 5;
|
||||
|
@ -79,14 +79,14 @@ fn main() {
|
|||
None => (),
|
||||
}
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
5. 🌟🌟 Ignoring remaining parts of the value with `..`
|
||||
```rust,editable
|
||||
|
||||
// fill the blank to make the code work
|
||||
// Fill the blank to make the code work
|
||||
fn main() {
|
||||
let numbers = (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048);
|
||||
|
||||
|
@ -97,11 +97,11 @@ fn main() {
|
|||
}
|
||||
}
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
6. 🌟🌟 Using pattern `&mut V` to match a mutable reference needs you to be very careful due to `V` being a value after matching
|
||||
6. 🌟🌟 Using pattern `&mut V` to match a mutable reference needs you to be very careful, due to `V` being a value after matching.
|
||||
```rust,editable
|
||||
|
||||
// FIX the error with least changing
|
||||
|
|
|
@ -1,29 +1,29 @@
|
|||
# Variables
|
||||
|
||||
### Binding and mutablity
|
||||
### Binding and mutability
|
||||
1. 🌟 A variable can be used only if it has been initialized.
|
||||
```rust,editable
|
||||
|
||||
// fix the error below with least modifying
|
||||
// Fix the error below with least amount of modification to the code
|
||||
fn main() {
|
||||
let x: i32; // uninitialized but using, ERROR !
|
||||
let y: i32; // uninitialized but also unusing, only warning
|
||||
let x: i32; // Uninitialized but used, ERROR !
|
||||
let y: i32; // Uninitialized but also unused, only a Warning !
|
||||
|
||||
assert_eq!(x, 5);
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
2. 🌟 Use `mut` to mark a variable as mutable.
|
||||
```rust,editable
|
||||
|
||||
// fill the blanks in code to make it compile
|
||||
// Fill the blanks in the code to make it compile
|
||||
fn main() {
|
||||
let __ = 1;
|
||||
let __ = 1;
|
||||
__ += 2;
|
||||
|
||||
assert_eq!(x, 3);
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -33,7 +33,7 @@ A scope is the range within the program for which the item is valid.
|
|||
3. 🌟
|
||||
```rust,editable
|
||||
|
||||
// fix the error below with least modifying
|
||||
// Fix the error below with least amount of modification
|
||||
fn main() {
|
||||
let x: i32 = 10;
|
||||
{
|
||||
|
@ -47,7 +47,7 @@ fn main() {
|
|||
4. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// fix the error with using of define_x
|
||||
// Fix the error with the use of define_x
|
||||
fn main() {
|
||||
println!("{}, world", x);
|
||||
}
|
||||
|
@ -63,7 +63,7 @@ You can declare a new variable with the same name as a previous variable, here w
|
|||
5. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// only modify `assert_eq!` to make the `println!` work(print `42` in terminal)
|
||||
// Only modify `assert_eq!` to make the `println!` work(print `42` in terminal)
|
||||
fn main() {
|
||||
let x: i32 = 5;
|
||||
{
|
||||
|
@ -73,7 +73,7 @@ fn main() {
|
|||
|
||||
assert_eq!(x, 12);
|
||||
|
||||
let x = 42;
|
||||
let x = 42;
|
||||
println!("{}", x); // Prints "42".
|
||||
}
|
||||
```
|
||||
|
@ -81,28 +81,28 @@ fn main() {
|
|||
6. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// remove a line in code to make it compile
|
||||
// Remove a line in the code to make it compile
|
||||
fn main() {
|
||||
let mut x: i32 = 1;
|
||||
x = 7;
|
||||
// shadowing and re-binding
|
||||
// Shadowing and re-binding
|
||||
let x = x;
|
||||
x += 3;
|
||||
|
||||
|
||||
let y = 4;
|
||||
// shadowing
|
||||
// Shadowing
|
||||
let y = "I can also be bound to text!";
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
### Unused varibles
|
||||
1. fix the warning below with :
|
||||
### Unused variables
|
||||
1. Fix the warning below with :
|
||||
|
||||
- 🌟 only one solution
|
||||
- 🌟🌟 two distinct solutions
|
||||
- 🌟 Only one solution
|
||||
- 🌟🌟 Two distinct solutions
|
||||
|
||||
> Note: none of the solutions is to remove the line `let x = 1`
|
||||
|
||||
|
@ -112,7 +112,7 @@ fn main() {
|
|||
let x = 1;
|
||||
}
|
||||
|
||||
// warning: unused variable: `x`
|
||||
// Warning: unused variable: `x`
|
||||
```
|
||||
|
||||
### Destructuring
|
||||
|
@ -122,7 +122,7 @@ fn main() {
|
|||
|
||||
```rust,editable
|
||||
|
||||
// fix the error below with least modifying
|
||||
// Fix the error below with least amount of modification
|
||||
fn main() {
|
||||
let (x, y) = (1, 2);
|
||||
x += 2;
|
||||
|
@ -130,12 +130,12 @@ fn main() {
|
|||
assert_eq!(x, 3);
|
||||
assert_eq!(y, 2);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
### Destructuring assignments
|
||||
Introducing in Rust 1.59: You can now use tuple, slice, and struct patterns as the left-hand side of an assignment.
|
||||
Introduced in Rust 1.59: You can now use tuple, slice, and struct patterns as the left-hand side of an assignment.
|
||||
|
||||
9. 🌟🌟
|
||||
|
||||
|
@ -147,10 +147,10 @@ fn main() {
|
|||
let (x, y);
|
||||
(x,..) = (3, 4);
|
||||
[.., y] = [1, 2];
|
||||
// fill the blank to make the code work
|
||||
// Fill the blank to make the code work
|
||||
assert_eq!([x,y], __);
|
||||
|
||||
println!("Success!")
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
<div align="center">
|
||||
<img height="150" src="https://github.com/sunface/rust-by-practice/blob/master/en/assets/logo.png?raw=true">
|
||||
<img src="https://github.com/sunface/rust-by-practice/blob/master/en/assets/header.png?raw=true">
|
||||
</div>
|
||||
|
||||
<p align="center">Practice Rust with challenging examples, exercises and projects</p>
|
||||
|
|
|
@ -1,28 +1,32 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
use std::mem::size_of_val;
|
||||
|
||||
fn main() {
|
||||
let c1 = 'a';
|
||||
assert_eq!(size_of_val(&c1),4);
|
||||
assert_eq!(size_of_val(&c1), 4);
|
||||
|
||||
let c2 = '中';
|
||||
assert_eq!(size_of_val(&c2),4);
|
||||
assert_eq!(size_of_val(&c2), 4);
|
||||
}
|
||||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let c1 = '中';
|
||||
print_char(c1);
|
||||
}
|
||||
}
|
||||
|
||||
fn print_char(c : char) {
|
||||
fn print_char(c: char) {
|
||||
println!("{}", c);
|
||||
}
|
||||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let _f: bool = false;
|
||||
|
@ -35,6 +39,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let f = true;
|
||||
|
@ -44,6 +49,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v0: () = ();
|
||||
|
@ -63,8 +69,10 @@ fn explicitly_ret_unit() -> () {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
use std::mem::size_of_val;
|
||||
|
||||
fn main() {
|
||||
let unit: () = ();
|
||||
// unit type does't occupy any memeory space
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// don't modify the following two lines!
|
||||
|
@ -14,6 +15,7 @@ fn sum(x: i32, y: i32) -> i32 {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
print();
|
||||
|
@ -26,6 +28,7 @@ fn print() -> () {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
never_return();
|
||||
|
@ -44,6 +47,7 @@ fn main() {
|
|||
|
||||
use std::thread;
|
||||
use std::time;
|
||||
|
||||
fn never_return() -> ! {
|
||||
// implement this function, don't modify fn signatures
|
||||
loop {
|
||||
|
@ -55,6 +59,7 @@ fn never_return() -> ! {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
println!("Success!");
|
||||
|
@ -69,7 +74,7 @@ fn get_option(tp: u8) -> Option<i32> {
|
|||
// TODO
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
never_return_fn()
|
||||
}
|
||||
|
||||
|
@ -97,6 +102,7 @@ fn never_return_fn() -> ! {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// FILL in the blank
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x: i32 = 5;
|
||||
|
@ -11,6 +12,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v: u16 = 38_u8 as u16;
|
||||
|
@ -18,6 +20,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x = 5;
|
||||
|
@ -31,6 +34,7 @@ fn type_of<T>(_: &T) -> String {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
assert_eq!(i8::MAX, 127);
|
||||
|
@ -39,6 +43,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v1 = 247_u8 + 8;
|
||||
|
@ -48,6 +53,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v = 1_024 + 0xff + 0o77 + 0b1111_1111;
|
||||
|
@ -56,6 +62,7 @@ fn main() {
|
|||
```
|
||||
|
||||
7.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x = 1_000.000_1; // f64
|
||||
|
@ -65,6 +72,7 @@ fn main() {
|
|||
```
|
||||
|
||||
8.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
assert!(0.1_f32+0.2_f32==0.3_f32);
|
||||
|
@ -78,6 +86,7 @@ fn main() {
|
|||
```
|
||||
|
||||
9.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut sum = 0;
|
||||
|
@ -94,6 +103,7 @@ fn main() {
|
|||
```
|
||||
|
||||
10.
|
||||
|
||||
```rust
|
||||
use std::ops::{Range, RangeInclusive};
|
||||
fn main() {
|
||||
|
@ -103,6 +113,7 @@ fn main() {
|
|||
```
|
||||
|
||||
11.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// Integer addition
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v = {
|
||||
|
@ -23,6 +24,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v = {
|
||||
|
@ -35,6 +37,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = sum(1 , 2);
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
// FILL in the blanks and FIX the erros
|
||||
use std::collections::HashMap;
|
||||
|
@ -29,6 +30,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
use std::collections::HashMap;
|
||||
fn main() {
|
||||
|
@ -73,9 +75,11 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
// FILL in the blanks
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn main() {
|
||||
// type inference lets us omit an explicit type signature (which
|
||||
// would be `HashMap<&str, u8>` in this example).
|
||||
|
@ -109,6 +113,7 @@ fn random_stat_buff() -> u8 {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
use std::collections::HashMap;
|
||||
|
||||
|
@ -144,19 +149,21 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
use std::collections::HashMap;
|
||||
fn main() {
|
||||
let v1 = 10;
|
||||
let mut m1 = HashMap::new();
|
||||
m1.insert(v1, v1);
|
||||
println!("v1 is still usable after inserting to hashmap : {}", v1);
|
||||
|
||||
// &str implements Copy trait
|
||||
let v2 = "hello";
|
||||
let mut m2 = HashMap::new();
|
||||
m2.insert(v2, v1);
|
||||
|
||||
assert_eq!(v2, "hello");
|
||||
fn main() {
|
||||
let v1 = 10;
|
||||
let mut m1 = HashMap::new();
|
||||
m1.insert(v1, v1);
|
||||
println!("v1 is still usable after inserting to hashmap : {}", v1);
|
||||
|
||||
// &str implements Copy trait
|
||||
let v2 = "hello";
|
||||
let mut m2 = HashMap::new();
|
||||
m2.insert(v2, v1);
|
||||
|
||||
assert_eq!(v2, "hello");
|
||||
}
|
||||
```
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s: String = String::from("hello, ");
|
||||
|
@ -36,6 +37,7 @@ fn borrow_string(s: &str) {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
// FILL in the blanks
|
||||
fn main() {
|
||||
|
@ -82,6 +84,7 @@ fn main() {
|
|||
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = String::from("hello, 世界");
|
||||
|
@ -102,6 +105,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
// FILL in the blanks
|
||||
fn main() {
|
||||
|
@ -123,6 +127,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::with_capacity(25);
|
||||
|
@ -139,6 +144,7 @@ fn main() {
|
|||
```
|
||||
|
||||
7.
|
||||
|
||||
```rust
|
||||
use std::mem;
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let arr: [u8; 3] = [1, 2, 3];
|
||||
|
@ -30,6 +31,7 @@ fn is_vec(v: &Vec<u8>) {}
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut v1 = Vec::from([1, 2, 4]);
|
||||
|
@ -45,7 +47,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
3.
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// array -> Vec
|
||||
|
@ -72,7 +75,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
4.
|
||||
4.
|
||||
|
||||
```rust,editable
|
||||
fn main() {
|
||||
let mut v = Vec::from([1, 2, 3]);
|
||||
|
@ -94,7 +98,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
5.
|
||||
5.
|
||||
|
||||
```rust
|
||||
// FIX the errors
|
||||
fn main() {
|
||||
|
@ -119,7 +124,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
6.
|
||||
6.
|
||||
|
||||
```rust
|
||||
// FIX the errors
|
||||
fn main() {
|
||||
|
@ -155,20 +161,22 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
7.
|
||||
7.
|
||||
|
||||
```rust
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum IpAddr {
|
||||
V4(String),
|
||||
V6(String),
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// FILL in the blank
|
||||
let v : Vec<IpAddr>= vec![
|
||||
let v: Vec<IpAddr> = vec![
|
||||
IpAddr::V4("127.0.0.1".to_string()),
|
||||
IpAddr::V6("::1".to_string())
|
||||
];
|
||||
|
||||
|
||||
// Comparing two enums need to derive the PartialEq trait
|
||||
assert_eq!(v[0], IpAddr::V4("127.0.0.1".to_string()));
|
||||
assert_eq!(v[1], IpAddr::V6("::1".to_string()));
|
||||
|
@ -177,7 +185,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
8.
|
||||
8.
|
||||
|
||||
```rust
|
||||
trait IpAddr {
|
||||
fn display(&self);
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let arr: [i32; 5] = [1, 2, 3, 4, 5];
|
||||
|
@ -8,12 +9,13 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// we can ignore parts of the array type or even the whole type, let the compiler infer it for us
|
||||
let arr0 = [1, 2, 3];
|
||||
let arr: [_; 3] = ['a', 'b', 'c'];
|
||||
|
||||
|
||||
// Arrays are stack allocated, `std::mem::size_of_val` return the bytes which array occupies
|
||||
// A char takes 4 byte in Rust: Unicode char
|
||||
assert!(std::mem::size_of_val(&arr) == 12);
|
||||
|
@ -21,6 +23,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let list: [i32; 100] = [1; 100];
|
||||
|
@ -31,6 +34,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// fix the error
|
||||
|
@ -39,10 +43,11 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let arr = ['a', 'b', 'c'];
|
||||
|
||||
|
||||
let ele = arr[0];
|
||||
|
||||
assert!(ele == 'a');
|
||||
|
@ -50,10 +55,11 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let names = [String::from("Sunfei"), "Sunface".to_string()];
|
||||
|
||||
|
||||
// `get` returns an Option<T>, it's safe to use
|
||||
let name0 = names.get(0).unwrap();
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
enum Number {
|
||||
Zero,
|
||||
|
@ -28,6 +29,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
enum Message {
|
||||
Quit,
|
||||
|
@ -43,6 +45,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
enum Message {
|
||||
Quit,
|
||||
|
@ -63,6 +66,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
#[derive(Debug)]
|
||||
enum Message {
|
||||
|
@ -75,14 +79,14 @@ enum Message {
|
|||
fn main() {
|
||||
let msgs: [Message; 3] = [
|
||||
Message::Quit,
|
||||
Message::Move{x:1, y:3},
|
||||
Message::ChangeColor(255,255,0)
|
||||
Message::Move { x: 1, y: 3 },
|
||||
Message::ChangeColor(255, 255, 0)
|
||||
];
|
||||
|
||||
for msg in msgs {
|
||||
show_message(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn show_message(msg: Message) {
|
||||
println!("{:?}", msg);
|
||||
|
@ -90,6 +94,7 @@ fn show_message(msg: Message) {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let five = Some(5);
|
||||
|
@ -113,6 +118,7 @@ fn plus_one(x: Option<i32>) -> Option<i32> {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
use crate::List::*;
|
||||
|
||||
|
@ -162,10 +168,10 @@ impl List {
|
|||
// `format!` is similar to `print!`, but returns a heap
|
||||
// allocated string instead of printing to the console
|
||||
format!("{}, {}", head, tail.stringify())
|
||||
},
|
||||
}
|
||||
Nil => {
|
||||
format!("Nil")
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let arr = [1, 2, 3];
|
||||
|
@ -9,18 +10,20 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let arr: [char; 3] = ['中', '国', '人'];
|
||||
|
||||
let slice = &arr[..2];
|
||||
|
||||
|
||||
// TIPS: slice( reference ) IS NOT an array, if it is an array, then `assert!` will passed: each of the two UTF-8 chars '中' and '国' occupies 3 bytes, 2 * 3 = 6
|
||||
assert!(std::mem::size_of_val(&slice) == 16);
|
||||
}
|
||||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let arr: [i32; 5] = [1, 2, 3, 4, 5];
|
||||
|
@ -30,6 +33,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = String::from("hello");
|
||||
|
@ -42,6 +46,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = "你好,世界";
|
||||
|
@ -52,6 +57,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::from("hello world");
|
||||
|
@ -63,8 +69,8 @@ fn main() {
|
|||
println!("the first word is: {}", word);
|
||||
|
||||
s.clear();
|
||||
|
||||
}
|
||||
|
||||
fn first_word(s: &str) -> &str {
|
||||
&s[..1]
|
||||
}
|
||||
|
|
|
@ -1,14 +1,16 @@
|
|||
1.
|
||||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s: &str = "hello, world";
|
||||
}
|
||||
```
|
||||
|
||||
2.
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s: Box<str> = "hello, world".into();
|
||||
let s: Box<str> = "hello, world".into();
|
||||
greetings(&s)
|
||||
}
|
||||
|
||||
|
@ -16,6 +18,7 @@ fn main() {
|
|||
println!("{}",s)
|
||||
}
|
||||
```
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s: Box<&str> = "hello, world".into();
|
||||
|
@ -27,7 +30,8 @@ fn greetings(s: &str) {
|
|||
}
|
||||
```
|
||||
|
||||
3.
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::new();
|
||||
|
@ -38,10 +42,11 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
4.
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::from("hello");
|
||||
let mut s = String::from("hello");
|
||||
s.push(',');
|
||||
s.push_str(" world");
|
||||
s += "!";
|
||||
|
@ -50,7 +55,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
5.
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = String::from("I like dogs");
|
||||
|
@ -61,7 +67,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
6.
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s1 = String::from("hello,");
|
||||
|
@ -72,10 +79,11 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
7.
|
||||
7.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = "hello, world".to_string();
|
||||
let s = "hello, world".to_string();
|
||||
greetings(s)
|
||||
}
|
||||
|
||||
|
@ -95,29 +103,31 @@ fn greetings(s: String) {
|
|||
}
|
||||
```
|
||||
|
||||
8.
|
||||
8.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = "hello, world".to_string();
|
||||
let s = "hello, world".to_string();
|
||||
let s1: &str = &s;
|
||||
}
|
||||
```
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = "hello, world";
|
||||
let s = "hello, world";
|
||||
let s1: &str = s;
|
||||
}
|
||||
```
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = "hello, world".to_string();
|
||||
let s = "hello, world".to_string();
|
||||
let s1: String = s;
|
||||
}
|
||||
```
|
||||
|
||||
9.
|
||||
9.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// You can use escapes to write bytes by their hexadecimal values
|
||||
|
@ -140,7 +150,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
10.
|
||||
10.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let raw_str = "Escapes don't work here: \x3F \u{211D}";
|
||||
|
@ -162,7 +173,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
11.
|
||||
11.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s1 = String::from("hi,中国");
|
||||
|
@ -174,7 +186,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
12.
|
||||
12.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
for c in "你好,世界".chars() {
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
struct Person {
|
||||
name: String,
|
||||
|
@ -16,6 +17,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
struct Unit;
|
||||
trait SomeTrait {
|
||||
|
@ -35,6 +37,7 @@ fn do_something_with_unit(u: Unit) { }
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
struct Color(i32, i32, i32);
|
||||
struct Point(i32, i32, i32);
|
||||
|
@ -52,6 +55,7 @@ fn check_color(p: Point) {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
struct Person {
|
||||
name: String,
|
||||
|
@ -72,6 +76,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
struct Person {
|
||||
name: String,
|
||||
|
@ -88,6 +93,7 @@ fn build_person(name: String, age: u8) -> Person {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
struct User {
|
||||
active: bool,
|
||||
|
@ -115,6 +121,7 @@ fn set_email(u: User) -> User {
|
|||
```
|
||||
|
||||
7.
|
||||
|
||||
```rust
|
||||
#[derive(Debug)]
|
||||
struct Rectangle {
|
||||
|
@ -136,6 +143,7 @@ fn main() {
|
|||
```
|
||||
|
||||
8.
|
||||
|
||||
```rust
|
||||
#[derive(Debug)]
|
||||
struct File {
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let _t0: (u8,i16) = (0, -1);
|
||||
|
@ -9,6 +10,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let t = ("i", "am", "sunface");
|
||||
|
@ -17,6 +19,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
|
||||
|
@ -25,6 +28,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let tup = (1, 6.4, "hello");
|
||||
|
@ -38,6 +42,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let (x, y, z);
|
||||
|
@ -52,6 +57,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let (x, y) = sum_multiply((2, 3));
|
||||
|
|
|
@ -2,13 +2,14 @@
|
|||
|
||||
2. `cargo new --lib hello-package1`
|
||||
|
||||
3. `hello-package` has a binary crate named `hello-package`, `src/main.rs` is the crate root.
|
||||
|
||||
3. `hello-package` has a binary crate named `hello-package`, `src/main.rs` is the crate root.
|
||||
|
||||
`hello-pacakge1` has a library crate named `hello-package1`, `src/lib.rs` is the crate root.
|
||||
|
||||
4. `hello-package1`
|
||||
|
||||
5.
|
||||
|
||||
```shell
|
||||
# FILL in the blanks
|
||||
.
|
||||
|
@ -20,6 +21,7 @@
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```shell
|
||||
# Create a package which contains
|
||||
# 1. three binary crates: `hello-package`, `main1` and `main2`
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
// in lib.rs
|
||||
mod front_of_house {
|
||||
|
@ -21,6 +22,7 @@ mod front_of_house {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
// in lib.rs
|
||||
pub mod front_of_house {
|
||||
|
@ -53,6 +55,7 @@ pub fn eat_at_restaurant() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
mod back_of_house {
|
||||
fn fix_incorrect_order() {
|
||||
|
@ -75,9 +78,8 @@ mod back_of_house {
|
|||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
// in src/lib.rs
|
||||
|
||||
|
@ -104,7 +106,6 @@ pub fn fix_incorrect_order() {
|
|||
pub fn cook_order() {}
|
||||
```
|
||||
|
||||
|
||||
```rust
|
||||
// in src/front_of_house/mod.rs
|
||||
|
||||
|
@ -136,8 +137,8 @@ pub fn take_payment() {}
|
|||
fn complain() {}
|
||||
```
|
||||
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
mod front_of_house;
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
use std::fmt::Result;
|
||||
use std::io::Result as IoResult;
|
||||
|
@ -7,6 +8,7 @@ fn main() {}
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
use std::collections::*;
|
||||
|
||||
|
@ -29,8 +31,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
3.
|
||||
|
||||
3.
|
||||
```rust
|
||||
// in lib.rs
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
struct test {
|
||||
list: Vec<i32>,
|
||||
|
|
|
@ -1,11 +1,12 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let n = 5;
|
||||
|
||||
if n < 0 {
|
||||
println!("{} is negative", n);
|
||||
} else if n > 0 {
|
||||
} else if n > 0 {
|
||||
println!("{} is positive", n);
|
||||
} else {
|
||||
println!("{} is zero", n);
|
||||
|
@ -14,6 +15,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let n = 5;
|
||||
|
@ -26,7 +28,7 @@ fn main() {
|
|||
} else {
|
||||
println!(", and is a big number, halve the number");
|
||||
|
||||
n / 2
|
||||
n / 2
|
||||
};
|
||||
|
||||
println!("{} -> {}", n, big_n);
|
||||
|
@ -34,9 +36,10 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
for n in 1..100 {
|
||||
for n in 1..100 {
|
||||
if n == 100 {
|
||||
panic!("NEVER LET THIS RUN")
|
||||
}
|
||||
|
@ -45,9 +48,10 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let names = [String::from("liming"),String::from("hanmeimei")];
|
||||
let names = [String::from("liming"), String::from("hanmeimei")];
|
||||
for name in &names {
|
||||
// do something with name...
|
||||
}
|
||||
|
@ -59,24 +63,26 @@ fn main() {
|
|||
for n in numbers {
|
||||
// do something with name...
|
||||
}
|
||||
|
||||
|
||||
println!("{:?}", numbers);
|
||||
}
|
||||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let a = [4, 3, 2, 1];
|
||||
|
||||
// iterate the indexing and value in 'a'
|
||||
for (i,v) in a.iter().enumerate() {
|
||||
println!("The {}th element is {}",i+1,v);
|
||||
for (i, v) in a.iter().enumerate() {
|
||||
println!("The {}th element is {}", i + 1, v);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// A counter variable
|
||||
|
@ -98,19 +104,20 @@ fn main() {
|
|||
n += 1;
|
||||
}
|
||||
|
||||
println!("n reached {}, soloop is over",n);
|
||||
println!("n reached {}, soloop is over", n);
|
||||
}
|
||||
```
|
||||
|
||||
7.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut n = 0;
|
||||
for i in 0..=100 {
|
||||
if n == 66 {
|
||||
break
|
||||
}
|
||||
n += 1;
|
||||
if n == 66 {
|
||||
break;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
|
||||
assert_eq!(n, 66);
|
||||
|
@ -118,16 +125,17 @@ fn main() {
|
|||
```
|
||||
|
||||
8.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut n = 0;
|
||||
for i in 0..=100 {
|
||||
if n != 66 {
|
||||
n+=1;
|
||||
continue;
|
||||
}
|
||||
|
||||
break
|
||||
if n != 66 {
|
||||
n += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
assert_eq!(n, 66);
|
||||
|
@ -135,6 +143,7 @@ fn main() {
|
|||
```
|
||||
|
||||
9.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut count = 0u32;
|
||||
|
@ -166,6 +175,7 @@ fn main() {
|
|||
```
|
||||
|
||||
10.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut counter = 0;
|
||||
|
@ -183,6 +193,7 @@ fn main() {
|
|||
```
|
||||
|
||||
11.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut count = 0;
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
#[derive(Debug)]
|
||||
struct Structure(i32);
|
||||
|
@ -10,7 +11,9 @@ fn main() {
|
|||
println!("Now {:?} will print!", Structure(3));
|
||||
}
|
||||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
#[derive(Debug)]
|
||||
struct Person {
|
||||
|
@ -26,6 +29,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
use std::fmt;
|
||||
|
||||
|
@ -48,6 +52,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4
|
||||
|
||||
```rust
|
||||
use std::fmt;
|
||||
|
||||
|
@ -79,6 +84,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
use std::fmt; // Import the `fmt` module.
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");// => Alice, this is Bob. Bob, this is Alice
|
||||
|
@ -9,6 +10,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
println!("{argument}", argument = "test"); // => "test"
|
||||
|
@ -24,6 +26,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// the following two are padding with 5 spaces
|
||||
|
@ -38,6 +41,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// left align
|
||||
|
@ -55,6 +59,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
println!("Hello {:5}!", 5); // => Hello 5!
|
||||
|
@ -69,6 +74,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v = 3.1415926;
|
||||
|
@ -84,6 +90,7 @@ fn main() {
|
|||
```
|
||||
|
||||
7.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = "Hello, world!";
|
||||
|
@ -97,6 +104,7 @@ fn main() {
|
|||
```
|
||||
|
||||
8.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
assert_eq!(format!("{:#b}", 27), "0b11011");
|
||||
|
@ -113,6 +121,7 @@ fn main() {
|
|||
```
|
||||
|
||||
9.
|
||||
|
||||
```rust
|
||||
fn get_person() -> String {
|
||||
String::from("sunface")
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s1 = "hello";
|
||||
|
@ -9,6 +10,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
print!("hello world, ");
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let color = String::from("green");
|
||||
|
@ -13,6 +14,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut count = 0;
|
||||
|
@ -38,6 +40,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// A non-copy type.
|
||||
|
@ -83,6 +86,7 @@ fn take<T>(_v: &T) {
|
|||
```
|
||||
|
||||
4、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let example_closure = |x| x;
|
||||
|
@ -95,6 +99,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5、
|
||||
|
||||
```rust
|
||||
fn fn_once<F>(func: F)
|
||||
where
|
||||
|
@ -126,11 +131,12 @@ fn main() {
|
|||
```
|
||||
|
||||
6、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::new();
|
||||
|
||||
let update_string = |str| s.push_str(str);
|
||||
let update_string = |str| s.push_str(str);
|
||||
|
||||
exec(update_string);
|
||||
|
||||
|
@ -143,6 +149,7 @@ fn exec<'a, F: FnMut(&'a str)>(mut f: F) {
|
|||
```
|
||||
|
||||
7、
|
||||
|
||||
```rust
|
||||
// A function which takes a closure as an argument and calls it.
|
||||
// <F> denotes that F is a "Generic type parameter"
|
||||
|
@ -197,6 +204,7 @@ fn main() {
|
|||
```
|
||||
|
||||
8、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::new();
|
||||
|
@ -212,6 +220,7 @@ fn exec<'a, F: FnOnce(&'a str) -> String>(mut f: F) {
|
|||
```
|
||||
|
||||
9、
|
||||
|
||||
```rust
|
||||
// Define a function which takes a generic `F` argument
|
||||
// bounded by `Fn`, and calls it
|
||||
|
@ -234,6 +243,7 @@ fn main() {
|
|||
```
|
||||
|
||||
10、
|
||||
|
||||
```rust
|
||||
/* Fill in the blank and fix the errror */
|
||||
// You can aslo use `impl FnOnce(i32) -> i32`
|
||||
|
@ -268,6 +278,7 @@ fn main() {
|
|||
```
|
||||
|
||||
11、
|
||||
|
||||
```rust
|
||||
// Every closure has its own type. Even if one closure has the same representation as another, their types are different.
|
||||
fn factory(x:i32) -> Box<dyn Fn(i32) -> i32> {
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let arr = [0; 10];
|
||||
|
@ -9,6 +10,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut v = Vec::new();
|
||||
|
@ -21,6 +23,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v1 = vec![1, 2];
|
||||
|
@ -48,6 +51,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let arr = vec![0; 10];
|
||||
|
@ -60,6 +64,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut names = vec!["Bob", "Frank", "Ferris"];
|
||||
|
@ -76,6 +81,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut values = vec![1, 2, 3];
|
||||
|
@ -90,6 +96,7 @@ fn main() {
|
|||
```
|
||||
|
||||
7、
|
||||
|
||||
```rust
|
||||
struct Fibonacci {
|
||||
curr: u32,
|
||||
|
@ -136,6 +143,7 @@ fn main() {
|
|||
```
|
||||
|
||||
8、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v1 = vec![1, 2, 3];
|
||||
|
@ -152,6 +160,7 @@ fn main() {
|
|||
```
|
||||
|
||||
9、
|
||||
|
||||
```rust
|
||||
use std::collections::HashMap;
|
||||
fn main() {
|
||||
|
@ -169,6 +178,7 @@ fn main() {
|
|||
```
|
||||
|
||||
10、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v1: Vec<i32> = vec![1, 2, 3];
|
||||
|
@ -180,6 +190,7 @@ fn main() {
|
|||
```
|
||||
|
||||
11、
|
||||
|
||||
```rust
|
||||
use std::collections::HashMap;
|
||||
fn main() {
|
||||
|
@ -192,6 +203,7 @@ fn main() {
|
|||
```
|
||||
|
||||
12、
|
||||
|
||||
```rust
|
||||
#[derive(PartialEq, Debug)]
|
||||
struct Shoe {
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
struct Container(i32, i32);
|
||||
|
||||
|
@ -53,6 +54,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
impl<T: Sub<Output = T>> Sub<Point<T>> for Point<T> {
|
||||
type Output = Self;
|
||||
|
@ -93,6 +95,7 @@ impl<T: Sub<Output = T>> Sub for Point<T> {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
trait Pilot {
|
||||
fn fly(&self) -> String;
|
||||
|
@ -134,6 +137,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
trait Person {
|
||||
fn name(&self) -> String;
|
||||
|
@ -209,6 +213,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
use std::fmt;
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
struct Array<T, const N: usize> {
|
||||
data : [T; N]
|
||||
|
@ -20,6 +21,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn print_array<T: std::fmt::Debug, const N: usize>(arr: [T; N]) {
|
||||
println!("{:?}", arr);
|
||||
|
@ -33,7 +35,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
3.
|
||||
3.
|
||||
|
||||
```rust
|
||||
#![allow(incomplete_features)]
|
||||
#![feature(generic_const_exprs)]
|
||||
|
@ -50,7 +53,7 @@ fn main() {
|
|||
check_size([0u8; 767]);
|
||||
check_size([0i32; 191]);
|
||||
check_size(["hello你好"; 47]); // &str is a string reference, containing a pointer and string length in it, so it takes two word long, in x86-64, 1 word = 8 bytes
|
||||
check_size(["hello你好".to_string(); 31]); // String is a smart pointer struct, it has three fields: pointer, length and capacity, each takes 8 bytes
|
||||
check_size([(); 31].map(|_| "hello你好".to_string())); // String is a smart pointer struct, it has three fields: pointer, length and capacity, each takes 8 bytes
|
||||
check_size(['中'; 191]); // A char takes 4 bytes in Rust
|
||||
}
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
struct A; // Concrete type `A`.
|
||||
struct S(A); // Concrete type `S`.
|
||||
|
@ -27,6 +28,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn sum<T:std::ops::Add<Output = T>>(x: T, y: T) -> T {
|
||||
x + y
|
||||
|
@ -39,8 +41,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
struct Point<T> {
|
||||
x: T,
|
||||
|
@ -54,6 +56,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
// modify this struct to make the code work
|
||||
struct Point<T, U> {
|
||||
|
@ -68,6 +71,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
struct Val<T> {
|
||||
val: T,
|
||||
|
@ -88,6 +92,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
struct Point<T, U> {
|
||||
x: T,
|
||||
|
@ -115,6 +120,7 @@ fn main() {
|
|||
```
|
||||
|
||||
7.
|
||||
|
||||
```rust
|
||||
struct Point<T> {
|
||||
x: T,
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
trait Bird {
|
||||
fn quack(&self) -> String;
|
||||
|
@ -58,6 +59,7 @@ fn hatch_a_bird(species: u8) ->Box<dyn Bird> {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
trait Bird {
|
||||
fn quack(&self);
|
||||
|
@ -101,6 +103,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
trait Draw {
|
||||
fn draw(&self) -> String;
|
||||
|
@ -139,6 +142,7 @@ fn draw_with_ref(x: &dyn Draw) {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
trait Foo {
|
||||
fn method(&self) -> String;
|
||||
|
@ -174,6 +178,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
trait MyTrait {
|
||||
fn f(&self) -> Self;
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
trait Hello {
|
||||
fn say_hi(&self) -> String {
|
||||
|
@ -37,6 +38,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
// `Centimeters`, a tuple struct that can be compared
|
||||
#[derive(PartialEq, PartialOrd)]
|
||||
|
@ -84,6 +86,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
use std::ops;
|
||||
|
||||
|
@ -101,6 +104,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
use std::ops;
|
||||
|
||||
|
@ -141,6 +145,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
// implement `fn summary` to make the code work
|
||||
// fix the errors without removing any code line
|
||||
|
@ -197,6 +202,7 @@ fn summary(t: &impl Summary) {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
struct Sheep {}
|
||||
struct Cow {}
|
||||
|
@ -272,6 +278,7 @@ fn main() {
|
|||
```
|
||||
|
||||
7.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
assert_eq!(sum(1, 2), 3);
|
||||
|
@ -298,6 +305,7 @@ where
|
|||
```
|
||||
|
||||
8.
|
||||
|
||||
```rust
|
||||
struct Pair<T> {
|
||||
x: T,
|
||||
|
@ -337,6 +345,7 @@ fn main() {
|
|||
```
|
||||
|
||||
9.
|
||||
|
||||
```rust
|
||||
fn example1() {
|
||||
// `T: Trait` is the commonly used way
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1、
|
||||
|
||||
```rust
|
||||
struct DoubleRef<'a,'b:'a, T> {
|
||||
r: &'a T,
|
||||
|
@ -9,8 +10,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
|
||||
2、
|
||||
|
||||
```rust
|
||||
struct ImportantExcerpt<'a> {
|
||||
part: &'a str,
|
||||
|
@ -29,6 +30,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3、
|
||||
|
||||
```rust
|
||||
fn f<'a, 'b>(x: &'a i32, mut y: &'b i32) where 'a: 'b {
|
||||
y = x; // &'a i32 is a subtype of &'b i32 because 'a: 'b
|
||||
|
@ -39,8 +41,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
|
||||
4、
|
||||
|
||||
```rust
|
||||
fn call_on_ref_zero<F>(f: F) where for<'a> F: Fn(&'a i32) {
|
||||
let zero = 0;
|
||||
|
@ -52,7 +54,9 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
Higher-ranked lifetimes may also be specified just before the trait: the only difference is the scope of the lifetime parameter, which extends only to the end of the following trait instead of the whole bound. This function is equivalent to the last one.
|
||||
Higher-ranked lifetimes may also be specified just before the trait: the only difference is the scope of the lifetime
|
||||
parameter, which extends only to the end of the following trait instead of the whole bound. This function is equivalent
|
||||
to the last one.
|
||||
|
||||
```rust
|
||||
fn call_on_ref_zero<F>(f: F) where F: for<'a> Fn(&'a i32) {
|
||||
|
@ -62,6 +66,7 @@ fn call_on_ref_zero<F>(f: F) where F: for<'a> Fn(&'a i32) {
|
|||
```
|
||||
|
||||
5、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut data = 10;
|
||||
|
@ -75,8 +80,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
|
||||
6、
|
||||
|
||||
```rust
|
||||
struct Interface<'b, 'a: 'b> {
|
||||
manager: &'b mut Manager<'a>
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
# Lifetime
|
||||
|
||||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let i = 3; // Lifetime for `i` starts. ────────────────┐
|
||||
|
@ -20,8 +22,8 @@ fn main() {
|
|||
} // Lifetime ends. ─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
|
||||
2. We can't borrow a item whose lifetime is smaller.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
{
|
||||
|
@ -38,6 +40,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3
|
||||
|
||||
```rust
|
||||
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
|
||||
if x.len() > y.len() {
|
||||
|
@ -51,6 +54,7 @@ fn main() {}
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn invalid_output() -> String {
|
||||
String::from("foo")
|
||||
|
@ -76,6 +80,7 @@ fn main() {}
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn print_refs<'a, 'b>(x: &'a i32, y: &'b i32) {
|
||||
println!("x is {} and y is {}", x, y);
|
||||
|
@ -98,6 +103,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
// A type `Borrowed` which houses a reference to an
|
||||
// `i32`. The reference to `i32` must outlive `Borrowed`.
|
||||
|
@ -135,6 +141,7 @@ fn main() {
|
|||
```
|
||||
|
||||
7. 🌟
|
||||
|
||||
```rust,editable
|
||||
/* Make it work */
|
||||
|
||||
|
@ -165,8 +172,8 @@ fn main()
|
|||
}
|
||||
```
|
||||
|
||||
|
||||
8. 🌟
|
||||
|
||||
```rust,editable
|
||||
|
||||
#[derive(Debug)]
|
||||
|
@ -193,6 +200,7 @@ fn main()
|
|||
```
|
||||
|
||||
9.
|
||||
|
||||
```rust
|
||||
struct ImportantExcerpt<'a> {
|
||||
part: &'a str,
|
||||
|
@ -207,8 +215,8 @@ impl<'a> ImportantExcerpt<'a> {
|
|||
fn main() {}
|
||||
```
|
||||
|
||||
|
||||
10.
|
||||
|
||||
```rust
|
||||
|
||||
fn nput(x: &i32) {
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let v: &str = "hello";
|
||||
|
@ -26,6 +27,7 @@ fn need_static(r : &'static str) {
|
|||
```
|
||||
|
||||
2、
|
||||
|
||||
```rust
|
||||
#[derive(Debug)]
|
||||
struct Config {
|
||||
|
@ -54,6 +56,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// Make a `string` literal and print it:
|
||||
|
@ -65,6 +68,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5、
|
||||
|
||||
```rust
|
||||
use std::fmt::Debug;
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
struct Rectangle {
|
||||
width: u32,
|
||||
|
@ -19,6 +20,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
#[derive(Debug)]
|
||||
struct TrafficLight {
|
||||
|
@ -26,12 +28,13 @@ struct TrafficLight {
|
|||
}
|
||||
|
||||
impl TrafficLight {
|
||||
pub fn show_state(&self) {
|
||||
pub fn show_state(&self) {
|
||||
println!("the current state is {}", self.color);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let light = TrafficLight{
|
||||
let light = TrafficLight {
|
||||
color: "red".to_owned(),
|
||||
};
|
||||
// Don't take the ownership of `light` here
|
||||
|
@ -42,6 +45,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
struct TrafficLight {
|
||||
color: String,
|
||||
|
@ -49,7 +53,7 @@ struct TrafficLight {
|
|||
|
||||
impl TrafficLight {
|
||||
// using `Self` to fill in the blank
|
||||
pub fn show_state(self: &Self) {
|
||||
pub fn show_state(self: &Self) {
|
||||
println!("the current state is {}", self.color);
|
||||
}
|
||||
|
||||
|
@ -58,10 +62,12 @@ impl TrafficLight {
|
|||
self.color = "green".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
#[derive(Debug)]
|
||||
struct TrafficLight {
|
||||
|
@ -82,6 +88,7 @@ impl TrafficLight {
|
|||
&self.color
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let light = TrafficLight::new();
|
||||
assert_eq!(light.get_state(), "red");
|
||||
|
@ -89,6 +96,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
struct Rectangle {
|
||||
width: u32,
|
||||
|
@ -107,10 +115,12 @@ impl Rectangle {
|
|||
self.width > other.width && self.height > other.height
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
#[derive(Debug)]
|
||||
enum TrafficLightColor {
|
||||
|
@ -135,6 +145,6 @@ fn main() {
|
|||
|
||||
assert_eq!(c.color(), "yellow");
|
||||
|
||||
println!("{:?}",c);
|
||||
println!("{:?}", c);
|
||||
}
|
||||
```
|
|
@ -1,4 +1,5 @@
|
|||
1、
|
||||
|
||||
```rust
|
||||
use std::fmt;
|
||||
|
||||
|
@ -17,6 +18,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2、
|
||||
|
||||
```rust
|
||||
struct Meters(u32);
|
||||
|
||||
|
@ -30,6 +32,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3、
|
||||
|
||||
```rust
|
||||
struct Years(i64);
|
||||
|
||||
|
@ -62,11 +65,13 @@ fn main() {
|
|||
```
|
||||
|
||||
4、Sometimes `newtype` pattern can provide extra readability.
|
||||
|
||||
```rust
|
||||
use std::ops::Add;
|
||||
use std::fmt::{self, format};
|
||||
|
||||
struct Meters(u32);
|
||||
|
||||
impl fmt::Display for Meters {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "There are still {} meters left", self.0)
|
||||
|
@ -80,9 +85,10 @@ impl Add for Meters {
|
|||
Self(self.0 + other.0)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let d = calculate_distance(Meters(10), Meters(20));
|
||||
assert_eq!(format!("{}",d), "There are still 30 meters left");
|
||||
assert_eq!(format!("{}", d), "There are still 30 meters left");
|
||||
}
|
||||
|
||||
/* implement calculate_distance */
|
||||
|
@ -92,6 +98,7 @@ fn calculate_distance(d1: Meters, d2: Meters) -> Meters {
|
|||
```
|
||||
|
||||
5、
|
||||
|
||||
```rust
|
||||
enum VeryVerboseEnumOfThingsToDoWithNumbers {
|
||||
Add,
|
||||
|
@ -109,6 +116,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6、
|
||||
|
||||
```rust
|
||||
enum VeryVerboseEnumOfThingsToDoWithNumbers {
|
||||
Add,
|
||||
|
@ -124,12 +132,11 @@ impl VeryVerboseEnumOfThingsToDoWithNumbers {
|
|||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
||||
}
|
||||
fn main() {}
|
||||
```
|
||||
|
||||
7、
|
||||
|
||||
```rust
|
||||
fn my_function<const N: usize>() -> [u32; N] {
|
||||
[123; N]
|
||||
|
@ -137,11 +144,12 @@ fn my_function<const N: usize>() -> [u32; N] {
|
|||
|
||||
fn main() {
|
||||
let arr = my_function::<5>();
|
||||
println!("{:?}",arr);
|
||||
println!("{:?}", arr);
|
||||
}
|
||||
```
|
||||
|
||||
8、
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s: &str = "Hello there!";
|
||||
|
@ -150,13 +158,14 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
|
||||
9、
|
||||
|
||||
```rust
|
||||
use std::fmt::Display;
|
||||
fn foobar_1(thing: &dyn Display) {}
|
||||
fn foobar_2(thing: Box<dyn Display>) {}
|
||||
|
||||
fn main() {
|
||||
}
|
||||
fn foobar_1(thing: &dyn Display) {}
|
||||
|
||||
fn foobar_2(thing: Box<dyn Display>) {}
|
||||
|
||||
fn main() {}
|
||||
```
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x = 5;
|
||||
|
@ -9,7 +10,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
2.
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x = 5;
|
||||
|
@ -20,7 +22,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
3.
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
@ -31,7 +34,8 @@ fn main() {
|
|||
fn borrow_object(s: &String) {}
|
||||
```
|
||||
|
||||
4.
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
@ -44,7 +48,8 @@ fn push_str(s: &mut String) {
|
|||
}
|
||||
```
|
||||
|
||||
5.
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
@ -56,7 +61,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
6.
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let c = '中';
|
||||
|
@ -77,7 +83,8 @@ fn get_addr(r: &char) -> String {
|
|||
}
|
||||
```
|
||||
|
||||
7.
|
||||
7.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = String::from("hello");
|
||||
|
@ -89,7 +96,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
8.
|
||||
8.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
//fix error by modifying this line
|
||||
|
@ -101,7 +109,8 @@ fn main() {
|
|||
fn borrow_object(s: &mut String) {}
|
||||
```
|
||||
|
||||
9.
|
||||
9.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
@ -114,7 +123,8 @@ fn main() {
|
|||
fn borrow_object(s: &String) {}
|
||||
```
|
||||
|
||||
10.
|
||||
10.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
@ -128,7 +138,8 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
11.
|
||||
11.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut s = String::from("hello, ");
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x = String::from("hello, world");
|
||||
|
@ -32,6 +33,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
// Don't modify code in main!
|
||||
fn main() {
|
||||
|
@ -49,6 +51,7 @@ fn take_ownership(s: String) -> String {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = give_ownership();
|
||||
|
@ -78,6 +81,7 @@ fn give_ownership() -> String {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = String::from("hello, world");
|
||||
|
@ -93,6 +97,7 @@ fn print_str(s: String) {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x = (1, 2, (), "hello");
|
||||
|
@ -102,6 +107,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let s = String::from("hello, ");
|
||||
|
@ -114,6 +120,7 @@ fn main() {
|
|||
```
|
||||
|
||||
7.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x = Box::new(5);
|
||||
|
@ -127,6 +134,7 @@ fn main() {
|
|||
```
|
||||
|
||||
8.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let t = (String::from("hello"), String::from("world"));
|
||||
|
@ -139,6 +147,7 @@ fn main() {
|
|||
```
|
||||
|
||||
9.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let t = (String::from("hello"), String::from("world"));
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
enum Direction {
|
||||
East,
|
||||
|
@ -20,6 +21,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let boolean = true;
|
||||
|
@ -38,6 +40,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
enum Message {
|
||||
Quit,
|
||||
|
@ -68,24 +71,26 @@ fn show_message(msg: Message) {
|
|||
assert_eq!(g, 255);
|
||||
assert_eq!(b, 0);
|
||||
}
|
||||
__ => println!("no data in these variants")
|
||||
_ => println!("no data in these variants")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let alphabets = ['a', 'E', 'Z', '0', 'x', '9' , 'Y'];
|
||||
|
||||
// fill the blank with `matches!` to make the code work
|
||||
for ab in alphabets {
|
||||
assert!(matches!(ab, 'a'..='z' | 'A'..='Z' | '0' | '9'))
|
||||
assert!(matches!(ab, 'a'..='z' | 'A'..='Z' | '0'..='9'))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
enum MyEnum {
|
||||
Foo,
|
||||
|
@ -107,6 +112,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let o = Some(7);
|
||||
|
@ -118,6 +124,7 @@ fn main() {
|
|||
```
|
||||
|
||||
7.
|
||||
|
||||
```rust
|
||||
enum Foo {
|
||||
Bar(u8)
|
||||
|
@ -133,6 +140,7 @@ fn main() {
|
|||
```
|
||||
|
||||
8.
|
||||
|
||||
```rust
|
||||
enum Foo {
|
||||
Bar,
|
||||
|
@ -152,6 +160,7 @@ fn main() {
|
|||
```
|
||||
|
||||
9.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let age = Some(30);
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {}
|
||||
fn match_number(n: i32) {
|
||||
|
@ -19,6 +20,7 @@ fn match_number(n: i32) {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
|
||||
struct Point {
|
||||
|
@ -40,6 +42,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
enum Message {
|
||||
Hello { id: i32 },
|
||||
|
@ -61,6 +64,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let num = Some(4);
|
||||
|
@ -74,6 +78,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let numbers = (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048);
|
||||
|
@ -88,6 +93,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut v = String::from("hello,");
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
use core::panic;
|
||||
|
||||
|
@ -20,21 +21,24 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
// MAKE the code work by fixing all panics
|
||||
fn main() {
|
||||
assert_eq!("abc".as_bytes(), [96, 97, 98]);
|
||||
assert_eq!("abc".as_bytes(), [97, 98, 99]);
|
||||
|
||||
let v = vec![1, 2, 3];
|
||||
let ele = v[3];
|
||||
let ele = v[2];
|
||||
// unwrap may panic when get return a None
|
||||
let ele = v.get(3).unwrap();
|
||||
let ele = v.get(2).unwrap();
|
||||
|
||||
// Sometimes, the compiler is unable to find the overflow errors for you in compile time ,so a panic will occur
|
||||
let v = production_rate_per_hour(2);
|
||||
|
||||
// because of the same reason as above, we have to wrap it in a function to make the panic occur
|
||||
divide(15, 0)
|
||||
divide(15, 1);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
|
||||
fn divide(x:u8, y:u8) {
|
||||
|
@ -42,7 +46,7 @@ fn divide(x:u8, y:u8) {
|
|||
}
|
||||
|
||||
fn production_rate_per_hour(speed: u8) -> f64 {
|
||||
let cph: u8 = 221;
|
||||
let cph: u8 = 21;
|
||||
match speed {
|
||||
1..=4 => (speed * cph) as f64,
|
||||
5..=8 => (speed * cph) as f64 * 0.9,
|
||||
|
@ -54,4 +58,4 @@ fn production_rate_per_hour(speed: u8) -> f64 {
|
|||
pub fn working_items_per_minute(speed: u8) -> u32 {
|
||||
(production_rate_per_hour(speed) / 60 as f64) as u32
|
||||
}
|
||||
```
|
||||
```
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
use std::num::ParseIntError;
|
||||
|
||||
|
@ -20,6 +21,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
use std::num::ParseIntError;
|
||||
|
||||
|
@ -38,6 +40,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read};
|
||||
|
@ -71,6 +74,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
use std::num::ParseIntError;
|
||||
|
||||
|
@ -100,6 +104,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
use std::num::ParseIntError;
|
||||
|
||||
|
@ -149,6 +154,7 @@ fn main() {
|
|||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
use std::num::ParseIntError;
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let decimal = 97.123_f32;
|
||||
|
@ -13,6 +14,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
// Suppress all warnings from casts which overflow.
|
||||
#![allow(overflowing_literals)]
|
||||
|
@ -24,6 +26,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
assert_eq!(1000 as u16, 1000);
|
||||
|
@ -58,6 +61,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut values: [i32; 2] = [1, 2];
|
||||
|
@ -75,6 +79,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let arr :[u64; 13] = [0; 13];
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
// impl From<bool> for i32
|
||||
|
@ -28,6 +29,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
// From is now included in `std::prelude`, so there is no need to introduce it into the current scope
|
||||
// use std::convert::From;
|
||||
|
@ -56,6 +58,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
use std::fs;
|
||||
use std::io;
|
||||
|
@ -92,6 +95,7 @@ fn main() {
|
|||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let n: i16 = 256;
|
||||
|
@ -111,6 +115,7 @@ fn main() {
|
|||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust,editable
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct EvenNum(i32);
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
1
|
||||
|
||||
```rust
|
||||
use std::fmt;
|
||||
|
||||
|
@ -23,6 +24,7 @@ fn main() {
|
|||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
// To use `from_str` method, you needs to introduce this trait into the current scope.
|
||||
use std::str::FromStr;
|
||||
|
@ -38,6 +40,7 @@ fn main() {
|
|||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
use std::str::FromStr;
|
||||
use std::num::ParseIntError;
|
||||
|
|
|
@ -1,23 +1,26 @@
|
|||
1.
|
||||
1.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x: i32 = 5; // uninitialized but using, ERROR !
|
||||
let y: i32; // uninitialized but also unusing, only warning
|
||||
println!("{} is equal to 5", x);
|
||||
println!("{} is equal to 5", x);
|
||||
}
|
||||
```
|
||||
|
||||
2.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut x = 1;
|
||||
x += 2;
|
||||
|
||||
println!("{} is equal to 3", x);
|
||||
let mut x = 1;
|
||||
x += 2;
|
||||
|
||||
println!("{} is equal to 3", x);
|
||||
}
|
||||
```
|
||||
|
||||
3.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x: i32 = 10;
|
||||
|
@ -25,15 +28,16 @@ fn main() {
|
|||
let y: i32 = 5;
|
||||
println!("The value of x is {} and value of y is {}", x, y);
|
||||
}
|
||||
println!("The value of x is {}", x);
|
||||
println!("The value of x is {}", x);
|
||||
}
|
||||
```
|
||||
|
||||
4.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x = define_x();
|
||||
println!("{}, world", x);
|
||||
println!("{}, world", x);
|
||||
}
|
||||
|
||||
fn define_x() -> String {
|
||||
|
@ -42,7 +46,20 @@ fn define_x() -> String {
|
|||
}
|
||||
```
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x = define_x();
|
||||
println!("{:?}, world", x);
|
||||
}
|
||||
|
||||
fn define_x() -> &'static str {
|
||||
let x = "hello";
|
||||
x
|
||||
}
|
||||
```
|
||||
|
||||
5.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let x: i32 = 5;
|
||||
|
@ -53,42 +70,45 @@ fn main() {
|
|||
|
||||
assert_eq!(x, 5);
|
||||
|
||||
let x = 42;
|
||||
let x = 42;
|
||||
println!("{}", x); // Prints "42".
|
||||
}
|
||||
```
|
||||
|
||||
6.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let mut x: i32 = 1;
|
||||
x = 7;
|
||||
// shadowing and re-binding
|
||||
let x = x;
|
||||
let x = x;
|
||||
// x += 3;
|
||||
|
||||
|
||||
let y = 4;
|
||||
// shadowing
|
||||
let y = "I can also be bound to text!";
|
||||
let y = "I can also be bound to text!";
|
||||
}
|
||||
```
|
||||
|
||||
7.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let _x = 1;
|
||||
let _x = 1;
|
||||
}
|
||||
```
|
||||
|
||||
```rust
|
||||
#[allow(unused_variables)]
|
||||
fn main() {
|
||||
let x = 1;
|
||||
let x = 1;
|
||||
}
|
||||
```
|
||||
|
||||
8.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let (mut x, y) = (1, 2);
|
||||
|
@ -110,12 +130,13 @@ fn main() {
|
|||
```
|
||||
|
||||
9.
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let (x, y);
|
||||
(x,..) = (3, 4);
|
||||
(x, ..) = (3, 4);
|
||||
[.., y] = [1, 2];
|
||||
// fill the blank to make the code work
|
||||
assert_eq!([x,y], [3,2]);
|
||||
assert_eq!([x, y], [3, 2]);
|
||||
}
|
||||
```
|
|
@ -45,8 +45,8 @@
|
|||
- [模块 Module](crate-module/module.md)
|
||||
- [使用use引入模块及受限可见性](crate-module/use-pub.md)
|
||||
- [注释和文档](comments-docs.md)
|
||||
- [格式化输出 todo](formatted-output.md)
|
||||
- [生命周期 todo](lifetime/intro.md)
|
||||
- [格式化输出](formatted-output.md)
|
||||
- [生命周期](lifetime/intro.md)
|
||||
- [生命周期基础](lifetime/basic.md)
|
||||
- [&'static 和 T: 'static](lifetime/static.md)
|
||||
- [深入生命周期](lifetime/advance.md)
|
||||
|
|
|
@ -3,6 +3,7 @@
|
|||
### 字符
|
||||
1. 🌟
|
||||
```rust, editable
|
||||
// 修改2处 `assert_eq!` 让代码工作
|
||||
|
||||
use std::mem::size_of_val;
|
||||
fn main() {
|
||||
|
@ -18,7 +19,7 @@ fn main() {
|
|||
|
||||
2. 🌟
|
||||
```rust, editable
|
||||
|
||||
// 修改一行让代码正常打印
|
||||
fn main() {
|
||||
let c1 = "中";
|
||||
print_char(c1);
|
||||
|
@ -33,7 +34,7 @@ fn print_char(c : char) {
|
|||
3. 🌟
|
||||
```rust, editable
|
||||
|
||||
// make println! work
|
||||
// 使成功打印
|
||||
fn main() {
|
||||
let _f: bool = false;
|
||||
|
||||
|
@ -72,12 +73,12 @@ fn main() {
|
|||
}
|
||||
|
||||
fn implicitly_ret_unit() {
|
||||
println!("I will returen a ()")
|
||||
println!("I will return a ()")
|
||||
}
|
||||
|
||||
// 不要使用下面的函数,它只用于演示!
|
||||
fn explicitly_ret_unit() -> () {
|
||||
println!("I will returen a ()")
|
||||
println!("I will return a ()")
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -94,4 +95,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/basic-types/char-bool.md)找到答案(在 solutions 路径下)
|
||||
|
|
|
@ -90,4 +90,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/basic-types/functions.md)找到答案(在 solutions 路径下)
|
||||
|
|
|
@ -163,4 +163,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/basic-types/numbers.md)找到答案(在 solutions 路径下)
|
||||
|
|
|
@ -61,4 +61,4 @@ fn sum(x: i32, y: i32) -> i32 {
|
|||
}
|
||||
```
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/basic-types/statements.md)找到答案(在 solutions 路径下)
|
||||
|
|
|
@ -204,4 +204,4 @@ fn main() {
|
|||
### 常用方法
|
||||
关于 String 的常用方法练习,可以查看[这里](../std/String.md).
|
||||
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/collections/String.md)(under the solutions path), but only use it when you need it
|
|
@ -140,7 +140,7 @@ fn main() {
|
|||
(Viking::new("Harald", "Iceland"), 12),
|
||||
]);
|
||||
|
||||
// 使用 derive 的方式来打印 vikong 的当前状态
|
||||
// 使用 derive 的方式来打印 viking 的当前状态
|
||||
for (viking, health) in &vikings {
|
||||
println!("{:?} has {} hp", viking, health);
|
||||
}
|
||||
|
@ -220,4 +220,4 @@ hash.insert(42, "the answer");
|
|||
assert_eq!(hash.get(&42), Some(&"the answer"));
|
||||
```
|
||||
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/collections/Hashmap.md)(under the solutions path), but only use it when you need it
|
||||
|
|
|
@ -245,4 +245,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/collections/Vector.md)(under the solutions path), but only use it when you need it
|
|
@ -1,5 +1,5 @@
|
|||
# 数组
|
||||
数组的类型是 `[T; Lengh]`, 就如你所看到的,数组的长度是类型签名的一部分,因此数组的长度必须在编译期就已知,例如你不能使用以下方式来声明一个数组:
|
||||
数组的类型是 `[T; Length]`,就如你所看到的,数组的长度是类型签名的一部分,因此数组的长度必须在编译期就已知,例如你不能使用以下方式来声明一个数组:
|
||||
```rust
|
||||
fn create_arr(n: i32) {
|
||||
let arr = [1; n];
|
||||
|
@ -83,4 +83,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/compound-types/array.md)找到答案(在 solutions 路径下)
|
|
@ -191,4 +191,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/compound-types/enum.md)找到答案(在 solutions 路径下)
|
|
@ -89,4 +89,4 @@ fn first_word(s: &str) -> &str {
|
|||
}
|
||||
```
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/compound-types/slice.md)找到答案(在 solutions 路径下)
|
|
@ -20,7 +20,7 @@ fn main() {
|
|||
|
||||
// 使用至少两种方法来修复错误
|
||||
fn main() {
|
||||
let s: Box<str> = "hello, world".into();
|
||||
let s: Box<str> = "hello, world".into();
|
||||
greetings(s)
|
||||
}
|
||||
|
||||
|
@ -50,7 +50,7 @@ fn main() {
|
|||
|
||||
// 修复所有错误,并且不要新增代码行
|
||||
fn main() {
|
||||
let s = String::from("hello");
|
||||
let s = String::from("hello");
|
||||
s.push(',');
|
||||
s.push(" world");
|
||||
s += "!".to_string();
|
||||
|
@ -98,7 +98,7 @@ fn main() {
|
|||
|
||||
// 使用至少两种方法来修复错误
|
||||
fn main() {
|
||||
let s = "hello, world";
|
||||
let s = "hello, world";
|
||||
greetings(s)
|
||||
}
|
||||
|
||||
|
@ -113,7 +113,7 @@ fn greetings(s: String) {
|
|||
|
||||
// 使用两种方法来解决错误,不要新增代码行
|
||||
fn main() {
|
||||
let s = "hello, world".to_string();
|
||||
let s = "hello, world".to_string();
|
||||
let s1: &str = s;
|
||||
}
|
||||
```
|
||||
|
@ -146,10 +146,9 @@ fn main() {
|
|||
|
||||
10. 🌟🌟🌟 有时候需要转义的字符很多,我们会希望使用更方便的方式来书写字符串: raw string.
|
||||
```rust,editable
|
||||
|
||||
/* 填空并修复所有错误 */
|
||||
fn main() {
|
||||
let raw_str = r"Escapes don't work here: \x3F \u{211D}";
|
||||
// 修改以下代码行,让它工作
|
||||
assert_eq!(raw_str, "Escapes don't work here: ? ℝ");
|
||||
|
||||
// 如果你希望在字符串中使用双引号,可以使用以下形式
|
||||
|
@ -255,4 +254,4 @@ fn main() {
|
|||
```
|
||||
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/compound-types/string.md)找到答案(在 solutions 路径下)
|
|
@ -218,4 +218,4 @@ fn main() {
|
|||
```
|
||||
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/compound-types/struct.md)找到答案(在 solutions 路径下)
|
||||
|
|
|
@ -77,4 +77,4 @@ fn sum_multiply(nums: (i32, i32)) -> (i32, i32) {
|
|||
```
|
||||
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/compound-types/tuple.md)找到答案(在 solutions 路径下)
|
|
@ -108,4 +108,4 @@ edition = "2021"
|
|||
可以看到,上面的 package 结构非常标准,你可以在很多 Rust 项目中看到该结构的身影。
|
||||
|
||||
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice) (under the solutions path), but only use it when you need it :)
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/crate-module/crate.md) (under the solutions path), but only use it when you need it :)
|
|
@ -192,4 +192,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice) (under the solutions path), but only use it when you need it :)
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/crate-module/module.md) (under the solutions path), but only use it when you need it :)
|
|
@ -67,4 +67,4 @@ pub mod a {
|
|||
至此,包与模块章节已经结束,关于 `hello-package` 的完整代码可以在[这里](https://github.com/sunface/rust-by-practice/tree/master/practices/hello-package) 找到.
|
||||
|
||||
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice) (under the solutions path), but only use it when you need it :)
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/crate-module/use-pub.md) (under the solutions path), but only use it when you need it :)
|
|
@ -35,4 +35,7 @@
|
|||
|
||||
你也可以在[以下地址](https://github.com/phil-opp/blog_os)找到完整的源代码。
|
||||
|
||||
### 7. mini-redis
|
||||
[mini-redis](https://github.com/tokio-rs/mini-redis) 是一个不完整的 Redis 客户端、服务器实现,由 tokio 官方出品,代码质量非常高,而且有详细的注释,非常适合学习 Rust 和异步编程。
|
||||
|
||||
**To be continued...**
|
|
@ -242,4 +242,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/flow-control.md)找到答案(在 solutions 路径下)
|
|
@ -1 +1,183 @@
|
|||
# Formatted output
|
||||
# 格式化输出
|
||||
|
||||
## 位置参数
|
||||
|
||||
1.🌟🌟
|
||||
```rust,edtiable
|
||||
|
||||
/* 填空 */
|
||||
fn main() {
|
||||
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");// => Alice, this is Bob. Bob, this is Alice
|
||||
assert_eq!(format!("{1}{0}", 1, 2), __);
|
||||
assert_eq!(format!(__, 1, 2), "2112");
|
||||
println!("Success!");
|
||||
}
|
||||
```
|
||||
|
||||
## 具名参数
|
||||
|
||||
2.🌟🌟
|
||||
```rust,editable
|
||||
fn main() {
|
||||
println!("{argument}", argument = "test"); // => "test"
|
||||
|
||||
/* 填空 */
|
||||
assert_eq!(format!("{name}{}", 1, __), "21");
|
||||
assert_eq!(format!(__,a = "a", b = 'b', c = 3 ), "a 3 b");
|
||||
|
||||
/* 修复错误 */
|
||||
// 具名参数必须放在其它参数后面
|
||||
println!("{abc} {1}", abc = "def", 2);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
## 字符串对齐
|
||||
|
||||
3.🌟🌟 默认情况下,通过空格来填充字符串
|
||||
```rust,editable
|
||||
fn main() {
|
||||
// 下面两个都是通过 5 个空格来填充
|
||||
println!("Hello {:5}!", "x"); // => "Hello x !"
|
||||
println!("Hello {:1$}!", "x", 5); // => "Hello x !"
|
||||
|
||||
/* 填空 */
|
||||
assert_eq!(format!("Hello __!", 5, "x"), "Hello x !");
|
||||
assert_eq!(format!("Hello __!", "x", width = 5), "Hello x !");
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
4.🌟🌟🌟 左对齐, 右对齐, 使用指定的字符填充
|
||||
```rust,editable
|
||||
fn main() {
|
||||
// 左对齐
|
||||
println!("Hello {:<5}!", "x"); // => Hello x !
|
||||
// 右对齐
|
||||
assert_eq!(format!("Hello __!", "x"), "Hello x!");
|
||||
// 居中对齐
|
||||
assert_eq!(format!("Hello __!", "x"), "Hello x !");
|
||||
|
||||
// 左对齐,并使用 `&` 填充
|
||||
assert_eq!(format!("Hello {:&<5}!", "x"), __);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
5.🌟🌟 我们还能使用 0 来填充数字
|
||||
```rust,editable
|
||||
fn main() {
|
||||
println!("Hello {:5}!", 5); // => Hello 5!
|
||||
println!("Hello {:+}!", 5); // => Hello +5!
|
||||
println!("Hello {:05}!", 5); // => Hello 00005!
|
||||
println!("Hello {:05}!", -5); // => Hello -0005!
|
||||
|
||||
/* 填空 */
|
||||
assert!(format!("{number:0>width$}", number=1, width=6) == __);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
## 精度
|
||||
6.🌟🌟 浮点数精度
|
||||
```rust,editable
|
||||
|
||||
/* 填空 */
|
||||
fn main() {
|
||||
let v = 3.1415926;
|
||||
|
||||
println!("{:.1$}", v, 4); // same as {:.4} => 3.1416
|
||||
|
||||
assert_eq!(format!("__", v), "3.14");
|
||||
assert_eq!(format!("__", v), "+3.14");
|
||||
assert_eq!(format!("__", v), "3");
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
7.🌟🌟🌟 字符串长度
|
||||
```rust,editable
|
||||
fn main() {
|
||||
let s = "Hello, world!";
|
||||
|
||||
println!("{0:.5}", s); // => Hello
|
||||
|
||||
assert_eq!(format!("Hello __!", 3, "abcdefg"), "Hello abc!");
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
## 二进制, 八进制, 十六进制
|
||||
|
||||
- format!("{}", foo) -> "3735928559"
|
||||
- format!("0x{:X}", foo) -> "0xDEADBEEF"
|
||||
- format!("0o{:o}", foo) -> "0o33653337357"
|
||||
|
||||
8.🌟🌟
|
||||
```rust,editable
|
||||
fn main() {
|
||||
assert_eq!(format!("__", 27), "0b11011");
|
||||
assert_eq!(format!("__", 27), "0o33");
|
||||
assert_eq!(format!("__", 27), "0x1b");
|
||||
assert_eq!(format!("__", 27), "0x1B");
|
||||
|
||||
println!("{:x}!", 27); // 没有前缀的十六进制 => 1b
|
||||
|
||||
println!("{:#010b}", 27); // 使用 0 来填充二进制,宽度为 10 => 0b00011011
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
## 捕获环境中的值
|
||||
9.🌟🌟🌟
|
||||
```rust,editable
|
||||
fn get_person() -> String {
|
||||
String::from("sunface")
|
||||
}
|
||||
|
||||
fn get_format() -> (usize, usize) {
|
||||
(4, 1)
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
let person = get_person();
|
||||
println!("Hello, {person}!");
|
||||
|
||||
let (width, precision) = get_format();
|
||||
let scores = [("sunface", 99.12), ("jack", 60.34)];
|
||||
/* 让下面的代码输出:
|
||||
sunface: 99.1
|
||||
jack: 60.3
|
||||
*/
|
||||
for (name, score) in scores {
|
||||
println!("{name}: __");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Others
|
||||
|
||||
**Example**
|
||||
```rust,editable
|
||||
fn main() {
|
||||
// 指数
|
||||
println!("{:2e}", 1000000000); // => 1e9
|
||||
println!("{:2E}", 1000000000); // => 1E9
|
||||
|
||||
// 指针地址
|
||||
let v= vec![1, 2, 3];
|
||||
println!("{:p}", v.as_ptr()); // => 0x600002324050
|
||||
|
||||
// 转义
|
||||
println!("Hello {{}}"); // => Hello {}
|
||||
}
|
||||
```
|
|
@ -9,7 +9,7 @@ pub trait CacheableItem: Clone + Default + fmt::Debug + Decodable + Encodable {
|
|||
}
|
||||
```
|
||||
|
||||
相比 `AsRef<[u8]> + Clone + fmt::Debug + Eq + Hash`, `Address` 的使用可以极大的极少其它类型在实现该特征时所需的模版代码.
|
||||
相比 `AsRef<[u8]> + Clone + fmt::Debug + Eq + Hash`, `Address` 的使用可以极大的减少其它类型在实现该特征时所需的模版代码.
|
||||
|
||||
1. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
@ -268,4 +268,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it :)
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/generics-traits/advanced-trait.md)(under the solutions path), but only use it when you need it :)
|
||||
|
|
|
@ -123,7 +123,7 @@ fn main() {
|
|||
check_size([0u8; 767]);
|
||||
check_size([0i32; 191]);
|
||||
check_size(["hello你好"; __]); // size of &str ?
|
||||
check_size(["hello你好".to_string(); __]); // size of String?
|
||||
check_size([(); __].map(|_| "hello你好".to_string())); // size of String?
|
||||
check_size(['中'; __]); // size of char ?
|
||||
}
|
||||
|
||||
|
|
|
@ -142,5 +142,5 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)
|
||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/generics-traits/generics.md)找到答案(在 solutions 路径下)
|
||||
|
||||
|
|
|
@ -223,4 +223,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it :)
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/generics-traits/trait-object.md)(under the solutions path), but only use it when you need it :)
|
|
@ -143,8 +143,8 @@ fn main() {
|
|||
let _one_second = Seconds(1);
|
||||
|
||||
println!("One second looks like: {:?}", _one_second);
|
||||
let _this_is_true = (_one_second == _one_second);
|
||||
let _this_is_true = (_one_second > _one_second);
|
||||
let _this_is_true = _one_second == _one_second;
|
||||
let _this_is_true = _one_second > _one_second;
|
||||
|
||||
let foot = Inches(12);
|
||||
|
||||
|
@ -175,7 +175,7 @@ use std::ops;
|
|||
// 实现 fn multiply 方法
|
||||
// 如上所述,`+` 需要 `T` 类型实现 `std::ops::Add` 特征
|
||||
// 那么, `*` 运算符需要实现什么特征呢? 你可以在这里找到答案: https://doc.rust-lang.org/core/ops/
|
||||
fn multipl
|
||||
fn multiply
|
||||
|
||||
fn main() {
|
||||
assert_eq!(6, multiply(2u8, 3u8));
|
||||
|
@ -467,4 +467,4 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it :)
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/generics-traits/traits.md)(under the solutions path), but only use it when you need it :)
|
||||
|
|
|
@ -1,26 +1,337 @@
|
|||
## 生命周期消除
|
||||
## 生命周期基础
|
||||
|
||||
编译器通过生命周期来确保所有的借用都是合法的,典型的,一个变量在创建时生命周期随之开始,销毁时生命周期也随之结束。
|
||||
|
||||
|
||||
## 生命周期的范围
|
||||
1、 🌟
|
||||
```rust,editable
|
||||
/* 为 `i` 和 `borrow2` 标注合适的生命周期范围 */
|
||||
|
||||
|
||||
// `i` 拥有最长的生命周期,因为它的作用域完整的包含了 `borrow1` 和 `borrow2` 。
|
||||
// 而 `borrow1` 和 `borrow2` 的生命周期并无关联,因为它们的作用域没有重叠
|
||||
fn main() {
|
||||
let i = 3;
|
||||
{
|
||||
let borrow1 = &i; // `borrow1` 生命周期开始. ──┐
|
||||
// │
|
||||
println!("borrow1: {}", borrow1); // │
|
||||
} // `borrow1` 生命周期结束. ──────────────────────────────────┘
|
||||
{
|
||||
let borrow2 = &i;
|
||||
|
||||
println!("borrow2: {}", borrow2);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. 🌟🌟
|
||||
|
||||
**示例**
|
||||
```rust
|
||||
fn print(s: &str); // elided
|
||||
fn print<'a>(s: &'a str); // expanded
|
||||
{
|
||||
let x = 5; // ----------+-- 'b
|
||||
// |
|
||||
let r = &x; // --+-- 'a |
|
||||
// | |
|
||||
println!("r: {}", r); // | |
|
||||
// --+ |
|
||||
} // ----------+
|
||||
```
|
||||
|
||||
fn debug(lvl: usize, s: &str); // elided
|
||||
fn debug<'a>(lvl: usize, s: &'a str); // expanded
|
||||
|
||||
fn substr(s: &str, until: usize) -> &str; // elided
|
||||
fn substr<'a>(s: &'a str, until: usize) -> &'a str; // expanded
|
||||
```rust,editable
|
||||
/* 像上面的示例一样,为 `r` 和 `x` 标准生命周期,然后从生命周期的角度. */
|
||||
|
||||
fn get_str() -> &str; // ILLEGAL
|
||||
fn main() {
|
||||
{
|
||||
let r; // ---------+-- 'a
|
||||
// |
|
||||
{ // |
|
||||
let x = 5; // -+-- 'b |
|
||||
r = &x; // | |
|
||||
} // -+ |
|
||||
// |
|
||||
println!("r: {}", r); // |
|
||||
} // ---------+
|
||||
}
|
||||
```
|
||||
|
||||
fn frob(s: &str, t: &str) -> &str; // ILLEGAL
|
||||
## 生命周期标注
|
||||
Rust 的借用检查器使用显式的生命周期标注来确定一个引用的合法范围。但是对于用户来说,我们在大多数场景下,都无需手动去标注生命周期,原因是编译器会在某些情况下自动应用生命周期消除规则。
|
||||
|
||||
fn get_mut(&mut self) -> &mut T; // elided
|
||||
fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded
|
||||
在了解编译器使用哪些规则帮我们消除生命周期之前,首先还是需要知道该如何手动标记生命周期。
|
||||
|
||||
fn args<T: ToCStr>(&mut self, args: &[T]) -> &mut Command // elided
|
||||
fn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command // expanded
|
||||
|
||||
fn new(buf: &mut [u8]) -> BufWriter; // elided
|
||||
fn new(buf: &mut [u8]) -> BufWriter<'_>; // elided (with `rust_2018_idioms`)
|
||||
fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a> // expanded
|
||||
#### 函数
|
||||
**大家先忽略生命周期消除规则**,让我们看看,函数签名中的生命周期有哪些限制:
|
||||
|
||||
- 需要为每个引用标注上合适的生命周期
|
||||
- 返回值中的引用,它的生命周期要么跟某个引用参数相同,要么是 `'statc`
|
||||
|
||||
**示例**
|
||||
```rust,editable
|
||||
// 引用参数中的生命周期 'a 至少要跟函数活得一样久
|
||||
fn print_one<'a>(x: &'a i32) {
|
||||
println!("`print_one`: x is {}", x);
|
||||
}
|
||||
|
||||
// 可变引用依然需要标准生命周期
|
||||
fn add_one<'a>(x: &'a mut i32) {
|
||||
*x += 1;
|
||||
}
|
||||
|
||||
// 下面代码中,每个参数都拥有自己独立的生命周期,事实上,这个例子足够简单,因此它们应该被标记上相同的生命周期 `'a`,但是对于复杂的例子而言,独立的生命周期标注是可能存在的
|
||||
fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) {
|
||||
println!("`print_multi`: x is {}, y is {}", x, y);
|
||||
}
|
||||
|
||||
// 返回一个通过参数传入的引用是很常见的,但是这种情况下需要标注上正确的生命周期
|
||||
fn pass_x<'a, 'b>(x: &'a i32, _: &'b i32) -> &'a i32 { x }
|
||||
|
||||
fn main() {
|
||||
let x = 7;
|
||||
let y = 9;
|
||||
|
||||
print_one(&x);
|
||||
print_multi(&x, &y);
|
||||
|
||||
let z = pass_x(&x, &y);
|
||||
print_one(z);
|
||||
|
||||
let mut t = 3;
|
||||
add_one(&mut t);
|
||||
print_one(&t);
|
||||
}
|
||||
```
|
||||
|
||||
3、 🌟
|
||||
```rust,editable
|
||||
/* 添加合适的生命周期标注,让下面的代码工作 */
|
||||
fn longest(x: &str, y: &str) -> &str {
|
||||
if x.len() > y.len() {
|
||||
x
|
||||
} else {
|
||||
y
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
```
|
||||
4、🌟🌟🌟
|
||||
```rust,editable
|
||||
/* 使用三种方法修复下面的错误 */
|
||||
fn invalid_output<'a>() -> &'a String {
|
||||
&String::from("foo")
|
||||
}
|
||||
|
||||
fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
5、🌟🌟
|
||||
```rust,editable
|
||||
// `print_refs` 有两个引用参数,它们的生命周期 `'a` 和 `'b` 至少得跟函数活得一样久
|
||||
fn print_refs<'a, 'b>(x: &'a i32, y: &'b i32) {
|
||||
println!("x is {} and y is {}", x, y);
|
||||
}
|
||||
|
||||
/* 让下面的代码工作 */
|
||||
fn failed_borrow<'a>() {
|
||||
let _x = 12;
|
||||
|
||||
// ERROR: `_x` 活得不够久does not live long enough
|
||||
let y: &'a i32 = &_x;
|
||||
|
||||
// 在函数内使用 `'a` 将会报错,原因是 `&_x` 的生命周期显然比 `'a` 要小
|
||||
// 你不能将一个小的生命周期强转成大的
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let (four, nine) = (4, 9);
|
||||
|
||||
|
||||
print_refs(&four, &nine);
|
||||
// 这里,four 和 nice 的生命周期必须要比函数 print_refs 长
|
||||
|
||||
failed_borrow();
|
||||
// `failed_borrow` 没有传入任何引用去限制生命周期 `'a`,因此,此时的 `'a` 生命周期是没有任何限制的,它默认是 `'static`
|
||||
}
|
||||
```
|
||||
|
||||
#### Structs
|
||||
6、 🌟
|
||||
```rust,editable
|
||||
/* 增加合适的生命周期标准,让代码工作 */
|
||||
|
||||
// `i32` 的引用必须比 `Borrowed` 活得更久
|
||||
#[derive(Debug)]
|
||||
struct Borrowed(&i32);
|
||||
|
||||
// 类似的,下面两个引用也必须比结构体 `NamedBorrowed` 活得更久
|
||||
#[derive(Debug)]
|
||||
struct NamedBorrowed {
|
||||
x: &i32,
|
||||
y: &i32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Either {
|
||||
Num(i32),
|
||||
Ref(&i32),
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let x = 18;
|
||||
let y = 15;
|
||||
|
||||
let single = Borrowed(&x);
|
||||
let double = NamedBorrowed { x: &x, y: &y };
|
||||
let reference = Either::Ref(&x);
|
||||
let number = Either::Num(y);
|
||||
|
||||
println!("x is borrowed in {:?}", single);
|
||||
println!("x and y are borrowed in {:?}", double);
|
||||
println!("x is borrowed in {:?}", reference);
|
||||
println!("y is *not* borrowed in {:?}", number);
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
7、 🌟🌟
|
||||
```rust,editable
|
||||
/* 让代码工作 */
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NoCopyType {}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Example<'a, 'b> {
|
||||
a: &'a u32,
|
||||
b: &'b NoCopyType
|
||||
}
|
||||
|
||||
fn main()
|
||||
{
|
||||
let var_a = 35;
|
||||
let example: Example;
|
||||
|
||||
{
|
||||
let var_b = NoCopyType {};
|
||||
|
||||
/* 修复错误 */
|
||||
example = Example { a: &var_a, b: &var_b };
|
||||
}
|
||||
|
||||
println!("(Success!) {:?}", example);
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
8、 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NoCopyType {}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[allow(dead_code)]
|
||||
struct Example<'a, 'b> {
|
||||
a: &'a u32,
|
||||
b: &'b NoCopyType
|
||||
}
|
||||
|
||||
/* 修复函数的签名 */
|
||||
fn fix_me(foo: &Example) -> &NoCopyType
|
||||
{ foo.b }
|
||||
|
||||
fn main()
|
||||
{
|
||||
let no_copy = NoCopyType {};
|
||||
let example = Example { a: &1, b: &no_copy };
|
||||
fix_me(&example);
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
## 方法
|
||||
方法的生命周期标注跟函数类似。
|
||||
|
||||
**示例**
|
||||
```rust,editable
|
||||
struct Owner(i32);
|
||||
|
||||
impl Owner {
|
||||
fn add_one<'a>(&'a mut self) { self.0 += 1; }
|
||||
fn print<'a>(&'a self) {
|
||||
println!("`print`: {}", self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut owner = Owner(18);
|
||||
|
||||
owner.add_one();
|
||||
owner.print();
|
||||
}
|
||||
```
|
||||
|
||||
9、🌟🌟
|
||||
```rust,editable
|
||||
/* 添加合适的生命周期让下面代码工作 */
|
||||
struct ImportantExcerpt {
|
||||
part: &str,
|
||||
}
|
||||
|
||||
impl ImportantExcerpt {
|
||||
fn level(&'a self) -> i32 {
|
||||
3
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
```
|
||||
|
||||
## 生命周期消除( Elision )
|
||||
|
||||
有一些生命周期的标注方式很常见,因此编译器提供了一些规则,可以让我们在一些场景下无需去标注生命周期,既节省了敲击键盘的繁琐,又能提升可读性。
|
||||
|
||||
这种规则被称为生命周期消除规则( Elision ),该规则之所以存在,仅仅是因为这些场景太通用了,为了方便用户而已。事实上对于借用检查器而言,该有的生命周期一个都不能少,只不过对于用户而言,可以省去一些。
|
||||
|
||||
|
||||
10、🌟🌟
|
||||
```rust,editable
|
||||
/* 移除所有可以消除的生命周期标注 */
|
||||
|
||||
fn nput<'a>(x: &'a i32) {
|
||||
println!("`annotated_input`: {}", x);
|
||||
}
|
||||
|
||||
fn pass<'a>(x: &'a i32) -> &'a i32 { x }
|
||||
|
||||
fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {
|
||||
x
|
||||
}
|
||||
|
||||
struct Owner(i32);
|
||||
|
||||
impl Owner {
|
||||
fn add_one<'a>(&'a mut self) { self.0 += 1; }
|
||||
fn print<'a>(&'a self) {
|
||||
println!("`print`: {}", self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct Person<'a> {
|
||||
age: u8,
|
||||
name: &'a str,
|
||||
}
|
||||
|
||||
enum Either<'a> {
|
||||
Num(i32),
|
||||
Ref(&'a i32),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
```
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue