├── .gitignore ├── LICENSE ├── README.md ├── go-01 ├── 1.md └── hello-world.go ├── go-02 ├── 1.md ├── constant_test.go └── fib_test.go ├── go-03 └── 1.md ├── go-04 └── 1.md ├── go-05 ├── 1.md └── loop_test.go ├── go-06 ├── 1.md └── array_test.go ├── go-07 ├── 1.md └── map_test.go ├── go-08 └── map_ext_test.go ├── go-09 └── string_test.go ├── go-10-11 └── func_test.go ├── go-12 └── encap_test.go ├── go-13 └── interface_test.go ├── go-14 └── extension_test.go ├── go-15 └── empty_interface_test.go ├── go-16 └── err_test.go ├── go-17 └── panic_recover_test.go ├── go-18 └── client │ └── package_test.go ├── go-19 └── 1.md ├── go-20 └── groutine_test.go ├── go-21 └── share_mem_test.go ├── go-22 ├── async_service_test.go └── channel.png ├── go-23 └── select_test.go ├── go-24 └── channel_close_test.go ├── go-25 └── cancel_test.go ├── go-26 └── cancel_by_context_test.go ├── go-27 └── once_test.go ├── go-28 └── first_response_test.go ├── go-29 └── all_done_test.go ├── go-30 └── obj_pool_test.go ├── go-31 └── sync_pool_test.go ├── go-32 └── function_test.go ├── go-33 └── benchmark_test.go ├── go-34 └── bdd_test.go ├── go-35 └── reflect_test.go ├── go-36 └── flexible_reflect_test.go ├── go-37 └── unsafe_test.go ├── go-38 └── 1.md ├── go-test-code ├── 1.md └── code_test.go └── src ├── go-19 └── module_package │ ├── get_remote_pack_test.go │ ├── glide.lock │ ├── glide.yaml │ └── vendor │ └── github.com │ └── easierway │ └── concurrent_map │ ├── LICENSE │ ├── README.md │ ├── concurrent_map.go │ ├── concurrent_map_benchmark_adapter.go │ ├── concurrent_map_test.go │ ├── int64_key.go │ ├── map_benchmark.png │ ├── map_benchmark_test.go │ ├── rwlock_map_benchmark_adapter.go │ ├── string_key.go │ └── sync_map_benchmark_adapter.go ├── go-38 ├── filter.go ├── pipe_filter_test.go └── split_filter.go └── series └── my_series.go /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | ### STS ### 3 | .apt_generated 4 | .classpath 5 | .factorypath 6 | .project 7 | .settings 8 | .springBeans 9 | .sts4-cache 10 | 11 | ### IntelliJ IDEA ### 12 | .idea 13 | *.iws 14 | *.iml 15 | *.ipr 16 | 17 | ### NetBeans ### 18 | /nbproject/private/ 19 | /build/ 20 | /nbbuild/ 21 | /dist/ 22 | /nbdist/ 23 | /.nb-gradle/ 24 | 25 | ## 忽略包文件,不提交 26 | bin 27 | pkg 28 | src/github.com 29 | go1.18 30 | ##这一章节包文件不大,直接上传,方便理解 31 | ##src/go-19/module_package/vendor/* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/] 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {fullname} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see [http://www.gnu.org/licenses/]. 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Destiny_pc Copyright (C) 2018 kaisec 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | [http://www.gnu.org/licenses/]. 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | [http://www.gnu.org/philosophy/why-not-lgpl.html]. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 序 2 | 开源协议:GPL-3.0 3 | 4 | 作者:[低调小熊猫] 5 | 6 | 地址:https://github.com/java-aodeng/golang-examples 7 | 8 | 意义:分享知识,提高自己 9 | 10 | ps:白天上班,晚上更新,尽量日更,比心 11 | 12 |

Go语言从入门到精通

13 | 14 | 第01章 关于 Go 语言的介绍 15 | 16 | 第02章 变量,常量以及与其他语言的差异 17 | 18 | 第03章 数据类型 19 | 20 | 第04章 运算符 21 | 22 | 第05章 条件和循环 23 | 24 | 第06章 数组和切片 25 | 26 | 第07章 Map 声明、元素访问及遍历 27 | 28 | [第08章 Map与工厂模式,在Go语言中实现Set](https://github.com/java-aodeng/golang-examples/blob/master/go-08/map_ext_test.go) 29 | 30 | [第09章 字符串](https://github.com/java-aodeng/golang-examples/blob/master/go-09/string_test.go) 31 | 32 | [第10章 Go与语言的函数 第11章 可变参数和defer](https://github.com/java-aodeng/golang-examples/blob/master/go-10-11/func_test.go) 33 | 34 | [第12章 行为的定义和实现](https://github.com/java-aodeng/golang-examples/blob/master/go-12/encap_test.go) 35 | 36 | [第13章 Go语言的相关接口](https://github.com/java-aodeng/golang-examples/blob/master/go-13/interface_test.go) 37 | 38 | [第14章 扩展与复用](https://github.com/java-aodeng/golang-examples/blob/master/go-14/extension_test.go) 39 | 40 | [第15章 不一样的接口类型,一样的多态](https://github.com/java-aodeng/golang-examples/blob/master/go-15/empty_interface_test.go) 41 | 42 | [第16章 编写好的错误处理](https://github.com/java-aodeng/golang-examples/blob/master/go-16/err_test.go) 43 | 44 | [第17章 panic和recover](https://github.com/java-aodeng/golang-examples/blob/master/go-17/panic_recover_test.go) 45 | 46 | [第18章 构建可复用的模块(包)](https://github.com/java-aodeng/golang-examples/blob/master/go-18/client/package_test.go) 47 | 48 | [第19章 依赖管理](https://github.com/java-aodeng/golang-examples/blob/master/src/go-19/module_package/get_remote_pack_test.go) 49 | 50 | [第20章 协程机制](https://github.com/java-aodeng/golang-examples/blob/master/go-20/groutine_test.go) 51 | 52 | [第21章 共享内存并发机制](https://github.com/java-aodeng/golang-examples/blob/master/go-21/share_mem_test.go) 53 | 54 | [第22章 CSP并发机制](https://github.com/java-aodeng/golang-examples/blob/master/go-22/async_service_test.go) 55 | 56 | [第23章 多路由选择和超时](https://github.com/java-aodeng/golang-examples/blob/master/go-23/select_test.go) 57 | 58 | [第24章 channel的关闭和广播](https://github.com/java-aodeng/golang-examples/blob/master/go-24/channel_close_test.go) 59 | 60 | [第25章 任务的取消](https://github.com/java-aodeng/golang-examples/blob/master/go-25/cancel_test.go) 61 | 62 | [第26章 Context与任务取消](https://github.com/java-aodeng/golang-examples/blob/master/go-26/cancel_by_context_test.go) 63 | 64 | [第27章 只运行一次](https://github.com/java-aodeng/golang-examples/blob/master/go-27/once_test.go) 65 | 66 | [第28章 仅需任意任务完成](https://github.com/java-aodeng/golang-examples/blob/master/go-28/first_response_test.go) 67 | 68 | [第29章 所有任务完成](https://github.com/java-aodeng/golang-examples/blob/master/go-29/all_done_test.go) 69 | 70 | [第30章 对象池](https://github.com/java-aodeng/golang-examples/blob/master/go-30/obj_pool_test.go) 71 | 72 | [第31章 sync.pool对象缓存](https://github.com/java-aodeng/golang-examples/blob/master/go-31/sync_pool_test.go) 73 | 74 | [第32章 单元测试](https://github.com/java-aodeng/golang-examples/blob/master/go-32/function_test.go) 75 | 76 | [第33章 Benchmark](https://github.com/java-aodeng/golang-examples/blob/master/go-33/benchmark_test.go) 77 | 78 | [第34章 BDD](https://github.com/java-aodeng/golang-examples/blob/master/go-34/bdd_test.go) 79 | 80 | [第35章 反射编程](https://github.com/java-aodeng/golang-examples/blob/master/go-35/reflect_test.go) 81 | 82 | [第36章 万能程序](https://github.com/java-aodeng/golang-examples/blob/master/go-36/flexible_reflect_test.go) 83 | 84 | [第37章 不安全编程](https://github.com/java-aodeng/golang-examples/blob/master/go-37/unsafe_test.go) 85 | 86 | [第38章 实现pipe-filter framework](https://github.com/java-aodeng/golang-examples/blob/master/src/go-38/pipe_filter_test.go) 87 | 88 | 第39章 实现micro-kernel framework 89 | 90 | 第40章 内置JSON解析 91 | 92 | 第41章 easyjson 93 | 94 | 第42章 构建Restful 95 | 96 | 第43章 性能分析工具 97 | 98 | 第44章 性能调优示例 99 | 100 | 第45章 别让性能被锁住 101 | 102 | 第46章 GC友好的代码 103 | 104 | 第47章 高效字符串连接 105 | 106 | 第48章 面向错误的设计 107 | 108 | 第49章 面向恢复的设计 109 | 110 | 第50章 Chaos Engineering 111 | 112 | 113 | -------------------------------------------------------------------------------- /go-01/1.md: -------------------------------------------------------------------------------- 1 | 第01章 关于 Go 语言的介绍 2 | 3 | ## 1.1 关于 Go 语言的介绍 4 | Go 语言是由谷歌公司在2007年开始开发的一门语言,目的是能在多核心时代高效编写网络应用程序。Go 语言的创始人 Robert Griesemer、Rob Pike 和 Ken Thompson 都是在计算机发展过程中作出过重要贡献的人。自从2009年11月正式公开发布后,Go 语言迅速席卷了整个互联网后端开发领域,其社区里不断涌现出类似 vitess、Docker、etcd、Consul 等重量级的开源项目。 5 | 6 | 计算机一直在演化,但是编程语言并没有以同样的速度演化。现在的手机,内置的 CPU 核数可能都多于我们使用的第一台电脑。高性能服务器拥有64核、128核,甚至更多核。但是我们依旧在使用为单核设计的技术在编程。 7 | 8 | 编程的技术同样在演化。大部分程序不再由单个开发者来完成,而是由处于不同时区、不同时间段工作的一组人来完成。大项目被分解为小项目,指派给不同的程序员,程序员开发完成后,再以可以在各个应用程序中交叉使用的库或者包的形式,提交给整个团队。 9 | 10 | 如今的程序员和公司比以往更加信任开源软件的力量。Go 语言是一种让代码分享更容易的编程语言。Go 语言自带一些工具,让使用别人写的包更容易,并且 Go 语言也让分享自己写的包更容易。 11 | 12 | ## 1.2 用Go解决现代编程难题 13 | Go 语言开发团队花了很长时间来解决当今软件开发人员面对的问题。开发人员在为项目选择语言时,不得不在快速开发和性能之间做出选择。C 和 C++这类语言提供了很快的执行速度,而 Ruby 和 Python 这类语言则擅长快速开发。Go 语言在这两者间架起了桥梁,不仅提供了高性能的语言,同时也让开发更快速。 14 | 15 | 在探索 Go 语言的过程中,读者会看到精心设计的特性以及简洁的语法。作为一门语言,Go 不仅定义了能做什么,还定义了不能做什么。Go 语言的语法简洁到只有几个关键字,便于记忆。Go 语言的编译器速度非常快,有时甚至会让人感觉不到在编译。所以,Go 开发者能显著减少等待项目构建的时间。因为 Go 语言内置并发机制,所以不用被迫使用特定的线程库,就能让软件扩展,使用更多的资源。Go 语言的类型系统简单且高效,不需要为面向对象开发付出额外的心智,让开发者能专注于代码复用。Go 语言还自带垃圾回收器,不需要用户自己管理内存。让我们快速浏览一下这些关键特性。 16 | 17 | ## 1.3 开发速度 18 | 编译一个大型的 C 或者 C++项目所花费的时间甚至比去喝杯咖啡的时间还长。 19 | 20 | Go 语言使用了更加智能的编译器,并简化了解决依赖的算法,最终提供了更快的编译速度。编译 Go 程序时,编译器只会关注那些直接被引用的库,而不是像 Java、C 和 C++那样,要遍历依赖链中所有依赖的库。因此,很多 Go 程序可以在1秒内编译完。在现代硬件上,编译整个 Go 语言的源码树只需要20秒。 21 | 22 | ## 1.4 并发 23 | 要开发出能充分利用硬件资源的应用程序是一件很难的事情。现代计算机都拥有多个核,但是大部分编程语言都没有有效的工具让程序可以轻易利用这些资源。这些语言需要写大量的线程同步代码来利用多个核,很容易导致错误。 24 | 25 | Go 语言对并发的支持是这门语言最重要的特性之一。goroutine 很像线程,但是它占用的内存远少于线程,使用它需要的代码更少。 26 | 27 | ## 1.5 Go 语言的类型系统 28 | Go 语言提供了灵活的、无继承的类型系统,无需降低运行性能就能最大程度上复用代码。这个类型系统依然支持面向对象开发,但避免了传统面向对象的问题。如果你曾经在复杂的 Java 和 C++程序上花数周时间考虑如何抽象类和接口,你就能意识到 Go语言的类型系统有多么简单。Go 开发者使用组合(composition)设计模式,只需简单地将一个类型嵌入到另一个类型,就能复用所有的功能。其他语言也能使用组合,但是不得不和继承绑在一起使用,结果使整个用法非常复杂,很难使用。在 Go 语言中,一个类型由其他更微小的类型组合而成,避免了传统的基于继承的模型。 29 | 30 | ## 1.6 内存管理 31 | 不当的内存管理会导致程序崩溃或者内存泄漏,甚至让整个操作系统崩溃。Go 语言拥有现代化的垃圾回收机制,能帮你解决这个难题。在其他系统语言(如 C 或者 C++)中,使用内存前要先分配这段内存,而且使用完毕后要将其释放掉。哪怕只做错了一件事,都可能导致程序崩溃或者内存泄漏。可惜,追踪内存是否还被使用本身就是十分艰难的事情,而要想支持多线程和高并发,更是让这件事难上加难。虽然 Go 语言的垃圾回收会有一些额外的开销,但是编程时,能显著降低开发难度。Go 语言把无趣的内存管理交给专业的编译器去做,而让程序员专注于更有趣的事情。 32 | 33 | ## 1.7 你好,Go 34 | 35 | ``` 36 | package main 37 | 38 | import "fmt" 39 | 40 | func main() { 41 | fmt.Print("hello world") 42 | } 43 | 44 | ``` 45 | 46 | 47 | -------------------------------------------------------------------------------- /go-01/hello-world.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | fmt.Print("hello world") 10 | os.Exit(8) 11 | } 12 | -------------------------------------------------------------------------------- /go-02/1.md: -------------------------------------------------------------------------------- 1 | 第02章 变量,常量以及与其他语言的差异 2 | 3 | 4 | ## 1.1 go语言实现一个Fibonacci数列 5 | ``` 6 | func TestFib(t *testing.T) { 7 | a:=1 8 | b:=1 9 | t.Log(a) 10 | for i:=0;i<5 ;i++ { 11 | t.Log("",b) 12 | temp:=a 13 | a=b 14 | b=temp+a 15 | } 16 | } 17 | ``` 18 | ## 1.2 go语言多变量赋值 ,一个赋值语句中实现对多个变量赋值 19 | ``` 20 | func TestExchange(t *testing.T) { 21 | a:=1 22 | b:=2 23 | a,b=b,a 24 | t.Log(a,b) 25 | } 26 | ``` 27 | ## 2.1定义常量 28 | 快速设置连续值,定义一周七天,值连续+1 29 | ``` 30 | const( 31 | Monday =iota +1 32 | Tuesday 33 | Wedensday 34 | Thurday 35 | Friday 36 | Saturday 37 | Sunday 38 | ) 39 | ``` 40 | ## 2.2 第一个比特位为1 其他位为0 表示Open 依此类推... 41 | ``` 42 | const ( 43 | Open =1 << iota 44 | Close 45 | Pending 46 | ) 47 | ``` 48 | ## 2.3 输出变量值 输出为1,6 49 | ``` 50 | func TestConstantTry(t *testing.T) { 51 | t.Log(Monday) 52 | t.Log(Saturday) 53 | } 54 | ``` 55 | ## 2.4比特位比较 1的二进制为0001 输出 true false false 56 | ``` 57 | func TestConstantTry1(t *testing.T) { 58 | a:=1 59 | t.Log(a&Open==Open,a&Close==Close,a&Pending==Pending) 60 | } 61 | ``` 62 | 63 | ## 总结: 64 | 变量我这里建议大家根据自己的习惯,选择简洁的赋值方式,去编写你的go程序,比较好 65 | 66 | 常量,大家了解下与java,c++这些常量连续赋值的一个简化方式就足够了 67 | -------------------------------------------------------------------------------- /go-02/constant_test.go: -------------------------------------------------------------------------------- 1 | package go_02 2 | 3 | import "testing" 4 | 5 | //定义常量 6 | 7 | //快速设置连续值,定义一周七天,值连续+1 8 | const( 9 | Monday =iota +1 10 | Tuesday 11 | Wedensday 12 | Thurday 13 | Friday 14 | Saturday 15 | Sunday 16 | ) 17 | 18 | //第一个比特位为1 其他位为0 表示Open 依此类推... 19 | const ( 20 | Open =1 << iota 21 | Close 22 | Pending 23 | ) 24 | 25 | //输出变量值 输出为1,6 26 | func TestConstantTry(t *testing.T) { 27 | t.Log(Monday) 28 | t.Log(Saturday) 29 | } 30 | 31 | //比特位比较 1的二进制为0001 输出 true false false 32 | func TestConstantTry1(t *testing.T) { 33 | a:=1 34 | t.Log(a&Open==Open,a&Close==Close,a&Pending==Pending) 35 | } -------------------------------------------------------------------------------- /go-02/fib_test.go: -------------------------------------------------------------------------------- 1 | package go_02 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | //定义变量 8 | 9 | //go语言实现一个Fibonacci数列 10 | func TestFib(t *testing.T) { 11 | a:=1 12 | b:=1 13 | t.Log(a) 14 | for i:=0;i<5 ;i++ { 15 | t.Log("",b) 16 | temp:=a 17 | a=b 18 | b=temp+a 19 | } 20 | } 21 | 22 | //go语言多变量赋值 ,一个赋值语句中实现对多个变量赋值 23 | func TestExchange(t *testing.T) { 24 | a:=1 25 | b:=2 26 | a,b=b,a 27 | t.Log(a,b) 28 | } -------------------------------------------------------------------------------- /go-03/1.md: -------------------------------------------------------------------------------- 1 | 第03章 数据类型 2 | 3 | ## 1.1 基本数据类型 4 | - bool 5 | - string 6 | - int,int8,int16,int32,int64 7 | - uint,uint8,uint16,uint32,uint64,uintptr 8 | - byte//alias for uint8 9 | - rune//alias for int32,represents a Unicode code point 10 | - float32,float64, 11 | - complex64,complex128 12 | 13 | ## 1.2 类型转化 14 | - Go 语言不允许隐式类型转换 15 | - 别名和原有类型也不能进行隐式类型转换 16 | 17 | ## 1.3 类型的预定于值 18 | - math.MaxInt64 19 | - math.MaxFloat64 20 | - math.MaxUint32 21 | 22 | ## 1.4 指针类型 23 | 与其他主要编程语言的差异 24 | - 不支持指针运算 25 | - string是值类型,其默认的初始化值为空字符串,而不是nil 26 | -------------------------------------------------------------------------------- /go-04/1.md: -------------------------------------------------------------------------------- 1 | 第04章 运算符 2 | 3 | ## 1.1 算术运算符 4 | - (+) 5 | - (-) 6 | - (*) 7 | - (/) 8 | - (%) 9 | - (--) 10 | - (++) 11 | - Go语言没有前置的++,-- 错误示例:(++a) 12 | 13 | ## 1.2 比较运算符 14 | - (==) 15 | - (!=) 16 | - (>) 17 | - (<) 18 | - (>=) 19 | - (<=) 20 | 21 | ## 1.2.1 用 == 比较数组 22 | - 相同维数且含有相同个数元素的数组才可以比较 23 | - 每个元素都相同的才相等 24 | 25 | ## 1.3 逻辑运算符 26 | - (&&) 27 | - (||) 28 | - (!) 29 | 30 | ## 1.4 位运算符 31 | - (&) 32 | - (|) 33 | - (^) 34 | - (<<) 35 | - (>>) 36 | 37 | ## 1.4.1 与其他主要编程语言的差异 38 | 39 | &^按位置清零 40 | 41 | 1 &^ 0 -- 1 42 | 1 &^ 1 -- 0 43 | 1 &^ 1 -- 0 44 | 0 &^ 0 -- 0 45 | 46 | 结论:右边是1,结果是0。右边是0,左边是什么就是什么。 47 | -------------------------------------------------------------------------------- /go-05/1.md: -------------------------------------------------------------------------------- 1 | 第05章 条件和循环 2 | 3 | ## 1.1 循环 4 | 与其他主要编程语言的差异 5 | 6 | - go语言仅支持循环关键字for 7 | 8 | ``` 9 | func TestWhileLoop(t *testing.T) { 10 | n:=0 11 | for n < 5 { 12 | t.Log(n) 13 | n++ 14 | } 15 | } 16 | ``` 17 | ## 1.2 if条件 18 | 与其他主要编程语言的差异 19 | 20 | - condition表达式结果必须为布尔值 21 | 22 | - 支持变量赋值 23 | 24 | 两段式写法,支持函数写法 25 | ``` 26 | func TestCondition(t *testing.T) { 27 | if a :=1==1;a { 28 | t.Log(a,"1") 29 | }else { 30 | t.Log(a,"2") 31 | } 32 | } 33 | ``` 34 | 35 | ## 1.3 switch条件 36 | 与其他主要编程语言的差异 37 | 38 | - 条件表达式不限制为常量或者整数 39 | - 单个case中,可以出现多个结果选项,使用逗号分隔 40 | - 与c语言等规则相反,go语言不需要用break来确定退出一个case 41 | - 可以不设定switch之后的条件表达式,在此种情况下,整个switch结构与多个if else 的逻辑作用相同 42 | 43 | ``` 44 | func TestSwitch(t *testing.T) { 45 | for i:=0;i<5 ;i++ { 46 | switch i { 47 | case 0,2: 48 | t.Log("111111") 49 | case 1,3: 50 | t.Log("222222") 51 | default: 52 | t.Log("000000") 53 | } 54 | } 55 | } 56 | 57 | func TestSwitch2(t *testing.T) { 58 | for i:=0;i<5 ;i++ { 59 | switch { 60 | case i%2==0: 61 | t.Log("111111%") 62 | case i%2==1: 63 | t.Log("222222%") 64 | default: 65 | t.Log("000000") 66 | } 67 | } 68 | } 69 | ``` 70 | -------------------------------------------------------------------------------- /go-05/loop_test.go: -------------------------------------------------------------------------------- 1 | package go_05 2 | 3 | import "testing" 4 | 5 | func TestWhileLoop(t *testing.T) { 6 | n:=0 7 | for n < 5 { 8 | t.Log(n) 9 | n++ 10 | } 11 | } 12 | 13 | func TestCondition(t *testing.T) { 14 | if a :=1==1;a { 15 | t.Log(a,"1") 16 | }else { 17 | t.Log(a,"2") 18 | } 19 | } 20 | 21 | func TestSwitch(t *testing.T) { 22 | for i:=0;i<5 ;i++ { 23 | switch i { 24 | case 0,2: 25 | t.Log("111111") 26 | case 1,3: 27 | t.Log("222222") 28 | default: 29 | t.Log("000000") 30 | } 31 | } 32 | } 33 | 34 | func TestSwitch2(t *testing.T) { 35 | for i:=0;i<5 ;i++ { 36 | switch { 37 | case i%2==0: 38 | t.Log("111111%") 39 | case i%2==1: 40 | t.Log("222222%") 41 | default: 42 | t.Log("000000") 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /go-06/1.md: -------------------------------------------------------------------------------- 1 | 第06章 数组和切片 2 | 3 | ## 1.1 数组的声明 4 | ``` 5 | func TestArray(t *testing.T) { 6 | var arr [3]int //声明并初始化长度 7 | t.Log(arr[1]) 8 | 9 | arr1:=[...]int{1,2,3}//声明同时初始化 10 | t.Log(arr1[1]) 11 | } 12 | ``` 13 | ## 1.2 遍历数组 14 | 15 | ``` 16 | func TestArrayTravel(t *testing.T) { 17 | arr:=[...]int{1,2,3,4} 18 | 19 | for idx,e:=range arr{ 20 | t.Log(idx,e) 21 | } 22 | 23 | t.Log(arr[1:len(arr)]) 24 | } 25 | ``` 26 | 27 | ## 1.3 数组截取 28 | a[开始索引(包含),结束索引(不包含)] 29 | ``` 30 | a:=[...]int{1,2,3} 31 | a[1,2] //2 32 | ``` 33 | 34 | ## 1.4 切片 35 | 36 | - len 元素的个数 37 | - cap 内部数组的容量 38 | - 切片共享存储修改会影响使用的数据,容易出错 (重点注意) 39 | ``` 40 | //切片 41 | func TestSliceInit(t *testing.T) { 42 | var s[] int //定义切片 43 | t.Log(len(s),cap(s)) 44 | s=append(s,1) //追加元素 45 | t.Log(len(s),cap(s)) 46 | 47 | s1:=[] int{1,2,3} 48 | t.Log(len(s1),cap(s1)) 49 | 50 | s2:=make ([]int,2,3) 51 | t.Log(len(s2),cap(s2)) 52 | } 53 | 54 | func TestSliceGrowing(t *testing.T) { 55 | s:=[]int{} 56 | for i:=0;i<10 ;i++ { 57 | s=append(s,i) 58 | t.Log(len(s),cap(s)) 59 | } 60 | } 61 | 62 | //切片共享存储修改会影响使用的数据,容易出错 63 | func TestSliceShare(t *testing.T) { 64 | s:=[]string{"1","2","3","4","5"} 65 | Q:=s[3:5] 66 | t.Log(Q,len(Q),cap(Q)) 67 | su:=s[1:3] 68 | t.Log(su,len(su),cap(su)) 69 | } 70 | ``` -------------------------------------------------------------------------------- /go-06/array_test.go: -------------------------------------------------------------------------------- 1 | package go_06 2 | 3 | import "testing" 4 | 5 | //数组 6 | func TestArray(t *testing.T) { 7 | var arr [3]int 8 | t.Log(arr[1]) 9 | 10 | arr1:=[...]int{1,2,3} 11 | t.Log(arr1[1]) 12 | } 13 | 14 | func TestArrayTravel(t *testing.T) { 15 | arr:=[...]int{1,2,3,4} 16 | 17 | for idx,e:=range arr{ 18 | t.Log(idx,e) 19 | } 20 | 21 | t.Log(arr[1:len(arr)]) 22 | } 23 | 24 | //切片 25 | func TestSliceInit(t *testing.T) { 26 | var s[] int 27 | t.Log(len(s),cap(s)) 28 | s=append(s,1) 29 | t.Log(len(s),cap(s)) 30 | 31 | s1:=[] int{1,2,3} 32 | t.Log(len(s1),cap(s1)) 33 | 34 | s2:=make ([]int,2,3) 35 | t.Log(len(s2),cap(s2)) 36 | } 37 | 38 | func TestSliceGrowing(t *testing.T) { 39 | s:=[]int{} 40 | for i:=0;i<10 ;i++ { 41 | s=append(s,i) 42 | t.Log(len(s),cap(s)) 43 | } 44 | } 45 | 46 | //共享数组修改会影响使用的数据,容易出错 47 | func TestSliceShare(t *testing.T) { 48 | s:=[]string{"1","2","3","4","5"} 49 | Q:=s[3:5] 50 | t.Log(Q,len(Q),cap(Q)) 51 | su:=s[1:3] 52 | t.Log(su,len(su),cap(su)) 53 | } -------------------------------------------------------------------------------- /go-07/1.md: -------------------------------------------------------------------------------- 1 | 第07章 Map 声明、元素访问及遍历 2 | 3 | ## 1.1 Map声明 4 | map key不存在,value默认会为0(重点注意) 5 | 6 | m:=map[string]int{"a":1,"aa":2,"aaa":3} 7 | 8 | m1:=map[string]int{} 9 | m1["a"]=1 10 | 11 | ``` 12 | func TestMap(t *testing.T) { 13 | m:=map[string]int{"a":1,"aa":2,"aaa":3} 14 | t.Log(m["a"]) 15 | } 16 | ``` -------------------------------------------------------------------------------- /go-07/map_test.go: -------------------------------------------------------------------------------- 1 | package go_07 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestMap(t *testing.T) { 8 | m := map[string]int{"a": 1, "aa": 2, "aaa": 3} 9 | t.Log(m["a"]) 10 | } 11 | 12 | func TestTraveMap(t *testing.T) { 13 | m := map[int]int{1: 1, 2: 4, 3: 9} 14 | 15 | for k, v := range m { 16 | t.Log(k, v) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /go-08/map_ext_test.go: -------------------------------------------------------------------------------- 1 | package go_08 2 | 3 | import "testing" 4 | 5 | func TestMapWithFunValue(t *testing.T) { 6 | m := map[int]func(op int) int{} 7 | m[1] = func(op int) int { return op } 8 | m[2] = func(op int) int { return op * op } 9 | m[3] = func(op int) int { return op * op * op } 10 | t.Log(m[1](2), m[2](2), m[3](2)) 11 | t.Log(m[3](3)) 12 | } 13 | 14 | func TestMapForSet(t *testing.T) { 15 | mySet := map[int]bool{} 16 | mySet[1] = true 17 | n := 3 18 | if mySet[n] { 19 | t.Logf("%d is existing", n) 20 | } else { 21 | t.Logf("%d is not existing", n) 22 | } 23 | mySet[3] = true 24 | t.Log(len(mySet)) 25 | delete(mySet, 1) 26 | n = 1 27 | if mySet[n] { 28 | t.Logf("%d is existing", n) 29 | } else { 30 | t.Logf("%d is not existing", n) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /go-09/string_test.go: -------------------------------------------------------------------------------- 1 | package go_09 2 | 3 | import ( 4 | "strconv" 5 | "strings" 6 | "testing" 7 | ) 8 | 9 | func TestString(t *testing.T) { 10 | var s string 11 | t.Log(s) //初始化为默认零值“” 12 | s = "hello" 13 | t.Log(len(s)) 14 | //s[1] = '3' //string是不可变的byte slice 15 | //s = "\xE4\xB8\xA5" //可以存储任何二进制数据 16 | s = "\xE4\xBA\xBB\xFF" 17 | t.Log(s) 18 | t.Log(len(s)) 19 | s = "中" 20 | t.Log(len(s)) //是byte数 21 | 22 | c := []rune(s) 23 | t.Log(len(c)) 24 | // t.Log("rune size:", unsafe.Sizeof(c[0])) 25 | t.Logf("中 unicode %x", c[0]) 26 | t.Logf("中 UTF8 %x", s) 27 | } 28 | 29 | func TestStringToRune(t *testing.T) { 30 | s := "中华人民共和国" 31 | for _, c := range s { 32 | t.Logf("%[1]c %[1]x", c) 33 | } 34 | } 35 | 36 | func TestStringFn(t *testing.T) { 37 | s := "A,B,C" 38 | parts := strings.Split(s, ",") 39 | for _, part := range parts { 40 | t.Log(part) 41 | } 42 | t.Log(strings.Join(parts, "-")) 43 | } 44 | 45 | func TestConv(t *testing.T) { 46 | s := strconv.Itoa(10) 47 | t.Log("str" + s) 48 | if i, err := strconv.Atoi("10"); err == nil { 49 | t.Log(10 + i) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /go-10-11/func_test.go: -------------------------------------------------------------------------------- 1 | package go_10_11 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | func returnMultiValues() (int, int) { 11 | return rand.Intn(10), rand.Intn(20) 12 | } 13 | 14 | func timeSpent(inner func(op int) int) func(op int) int { 15 | return func(n int) int { 16 | start := time.Now() 17 | ret := inner(n) 18 | fmt.Println("time spent:", time.Since(start).Seconds()) 19 | return ret 20 | } 21 | } 22 | 23 | func slowFun(op int) int { 24 | time.Sleep(time.Second * 1) 25 | return op 26 | } 27 | 28 | func TestFn(t *testing.T) { 29 | a, _ := returnMultiValues() 30 | t.Log(a) 31 | tsSF := timeSpent(slowFun) 32 | t.Log(tsSF(10)) 33 | } 34 | 35 | //可变参数 36 | func Sum(ops ...int) int { 37 | ret := 0 38 | for _, op := range ops { 39 | ret += op 40 | } 41 | return ret 42 | } 43 | 44 | func TestVarParam(t *testing.T) { 45 | t.Log(Sum(1, 2, 3, 4)) 46 | t.Log(Sum(1, 2, 3, 4, 5)) 47 | } 48 | 49 | func Clear() { 50 | fmt.Println("Clear resources.") 51 | } 52 | 53 | func TestDefer(t *testing.T) { 54 | defer Clear() //异常之后执行 类型java的finally执行顺序 55 | fmt.Println("Start") 56 | panic("err") //抛异常 57 | } 58 | -------------------------------------------------------------------------------- /go-12/encap_test.go: -------------------------------------------------------------------------------- 1 | package go_12 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "unsafe" 7 | ) 8 | 9 | type Employee struct { 10 | Id string 11 | Name string 12 | Age int 13 | } 14 | 15 | //func (e *Employee) String() string { 16 | // fmt.Printf("Address is %x", unsafe.Pointer(&e.Name)) 17 | // return fmt.Sprintf("ID:%s/Name:%s/Age:%d", e.Id, e.Name, e.Age) 18 | //} 19 | 20 | //整个结构被复制 数据地址不一致 空间开销更大 21 | func (e Employee) String() string { 22 | fmt.Printf("Address is %x\n", unsafe.Pointer(&e.Name)) 23 | return fmt.Sprintf("ID:%s-Name:%s-Age:%d", e.Id, e.Name, e.Age) 24 | } 25 | 26 | func TestCreateEmployeeObj(t *testing.T) { 27 | e := Employee{"0", "Bob", 20} 28 | e1 := Employee{Name: "Mike", Age: 30} 29 | e111 := Employee{Id: "1", Name: "Mike", Age: 30} 30 | e2 := new(Employee) //返回指针 31 | e2.Id = "2" 32 | e2.Age = 22 33 | e2.Name = "Rose" 34 | t.Log(e) 35 | t.Log(e1) 36 | t.Log(e1.Id) 37 | t.Log(e2) 38 | t.Logf("e is %T", e) 39 | t.Logf("e2 is %T", e2) 40 | t.Log(e111) 41 | } 42 | 43 | func TestStructOperations(t *testing.T) { 44 | e := Employee{"0", "Bob", 20} 45 | fmt.Printf("Address is %x\n", unsafe.Pointer(&e.Name)) 46 | t.Log(e.String()) 47 | } 48 | -------------------------------------------------------------------------------- /go-13/interface_test.go: -------------------------------------------------------------------------------- 1 | package go_13 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | //定义一个接口 8 | type Programmer interface { 9 | WriteHelloWorld() string 10 | } 11 | 12 | //实现接口 13 | type GoProgrammer struct { 14 | } 15 | 16 | func (g *GoProgrammer) WriteHelloWorld() string { 17 | return "hello world" 18 | } 19 | 20 | func Test(t *testing.T) { 21 | var p Programmer 22 | p = new(GoProgrammer) 23 | t.Log(p.WriteHelloWorld()) 24 | } 25 | -------------------------------------------------------------------------------- /go-14/extension_test.go: -------------------------------------------------------------------------------- 1 | package go_14 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | //go语言扩展类似java的继承 但又不完全是 9 | //这是一只猪类 10 | type Pig struct { 11 | } 12 | 13 | func (p *Pig) Speak() { 14 | fmt.Print("我是猪") 15 | } 16 | 17 | func (p *Pig) MyNameIs(name string) { 18 | p.Speak() 19 | fmt.Print("my name is" + name) 20 | } 21 | 22 | //这是一条狗类 继承于猪类 go继承没看到啥关键字,就直接像下面这样写就行了 23 | type Dog struct { 24 | Pig 25 | } 26 | 27 | func (d *Dog) Speak() { 28 | //类似于java的重载 29 | fmt.Print("我不是猪,我是狗") 30 | } 31 | 32 | func (d *Dog) MyNameIs(name string) { 33 | d.Speak() 34 | fmt.Print("my name is" + name) 35 | } 36 | 37 | //这是一个傻逼 38 | type SB struct { 39 | Pig 40 | } 41 | 42 | func (s *SB) Speak() { 43 | fmt.Print("我是一个傻逼") 44 | } 45 | 46 | func TestDog(t *testing.T) { 47 | dog := new(Dog) 48 | dog.MyNameIs("你爸爸") 49 | 50 | fmt.Print("========\n") 51 | 52 | sb := new(SB) 53 | sb.MyNameIs("你爷爷") 54 | } 55 | 56 | //运行结果 57 | //=== RUN TestDog 58 | //我不是猪,我是狗my name is你爸爸======== 59 | //我是猪my name is你爷爷--- PASS: TestDog (0.00s) 60 | //PASS 61 | -------------------------------------------------------------------------------- /go-15/empty_interface_test.go: -------------------------------------------------------------------------------- 1 | package go_15 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | //go语言的空接口与断言 9 | //1.go语言的空接口可以表示任何类型, 10 | //2.通过断言来将空接口转换为制定类型 11 | //如:v,ok :=p.(int) //ok=true时为转换成功 12 | func DoSomething(p interface{}) { 13 | switch v := p.(type) { 14 | case int: 15 | fmt.Print("Integer类型的", v) 16 | case string: 17 | fmt.Print("String类型的", v) 18 | default: 19 | fmt.Print("未知类型的") 20 | } 21 | } 22 | 23 | //这里主要是体会一下go语言的多态 与其他语言的区别 24 | func TestEmptyInterfaceAssertion(t *testing.T) { 25 | DoSomething(1) 26 | fmt.Print("\n") 27 | DoSomething("1") 28 | fmt.Print("\n") 29 | DoSomething(1.1) 30 | } 31 | 32 | //运行结果 33 | //=== RUN TestEmptyInterfaceAssertion 34 | //Integer类型的1 35 | //String类型的1 36 | //未知类型的--- PASS: TestEmptyInterfaceAssertion (0. 00s) 37 | //PASS 38 | -------------------------------------------------------------------------------- /go-16/err_test.go: -------------------------------------------------------------------------------- 1 | package go_16 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "strconv" 7 | "testing" 8 | ) 9 | 10 | //Go的错误机制 11 | //1、这里需要注意:go没有异常机制,都自己写判断实现的 12 | //2、error类型实现error接口 type error interface{Error() string} 13 | //3、可以通过errors.New来创建错误实例 14 | 15 | //这里创建两个错误实列,这一步,类似于java的自定义异常 16 | var LessThanTwoError = errors.New("参数小于 2") 17 | var LargerThenHundredError = errors.New("参数大于 100") 18 | 19 | //定义一个斐波那契列方法,这个方法前面做逻辑判断,返回自定义error实列 20 | func GetFibonacci(n int) ([]int, error) { 21 | //参数校验,不满足返回定义的自定义异常 22 | if n < 2 { 23 | return nil, LessThanTwoError 24 | } 25 | if n > 100 { 26 | return nil, LargerThenHundredError 27 | } 28 | fibList := []int{1, 1} 29 | //斐波那契列,小学数学题 30 | for i := 2; i < n; i++ { 31 | fibList = append(fibList, fibList[i-2]+fibList[i-1]) 32 | } 33 | return fibList, nil 34 | } 35 | 36 | //优化处理,及早失败,避免嵌套,这一步类似于java的全局异常抓取处理 37 | func GetFibonacci2(str string) { 38 | var ( 39 | i int 40 | err error 41 | list []int 42 | ) 43 | //传入的参数string类型转换为int类型,转换不了,返回异常 44 | if i, err = strconv.Atoi(str); err != nil { 45 | fmt.Println("Error", err) 46 | return 47 | } 48 | //调用斐波那契列方法,异常不为空,返回异常 49 | if list, err = GetFibonacci(i); err != nil { 50 | fmt.Println("Error", err) 51 | return 52 | } 53 | fmt.Println(list) 54 | 55 | } 56 | 57 | //测试 58 | func TestGetFibonacci(t *testing.T) { 59 | //GetFibonacci2("test")//运行结果,类型转换失败异常 Error strconv.Atoi: parsing "test": invalid syntax 60 | //GetFibonacci2("1")//运行结果,参数校验异常 Error 参数小于 2 61 | //GetFibonacci2("101") //运行结果,参数校验异常 Error 参数大于 100 62 | GetFibonacci2("10") //运行结果,运行正常,实现斐波那契列 [1 1 2 3 5 8 13 21 34 55] 63 | } 64 | -------------------------------------------------------------------------------- /go-17/panic_recover_test.go: -------------------------------------------------------------------------------- 1 | package go_17 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "log" 7 | "os" 8 | "testing" 9 | ) 10 | 11 | //panic 12 | //用于主动抛出错误,类似于java的抛出异常 13 | //panic用于不可以恢复的错误 14 | //panic退出前回执行defer指定的内容 15 | 16 | //panic 和os.Exit的区别 17 | //os.Exit退出时不会调用defer指定的函数 18 | //os.Exit退出时不输出当前调用栈信息 19 | 20 | //recover 21 | //用于捕获panic抛出的错误,类似于java的异常捕获try{}catch 22 | 23 | //使用Exit退出程序 24 | func TestExit(t *testing.T) { 25 | defer func() { 26 | fmt.Print("我是退出前回执的内容") 27 | }() 28 | fmt.Print("Start--》") 29 | os.Exit(-1) 30 | } 31 | 32 | //运行结果 :可以看到退出后没有执行defer里面的内容 33 | //=== RUN TestExit 34 | //Start--》 35 | 36 | //使用panic抛出异常 37 | func TestPainc(t *testing.T) { 38 | defer func() { 39 | fmt.Print("我是退出前回执的内容") 40 | }() 41 | fmt.Print("Start--》") 42 | panic(errors.New("异常退出")) 43 | } 44 | 45 | //运行结果 :可以看到退出后执行defer里面的内容,并且输出当前调用栈信息 46 | //=== RUN TestPainc 47 | //Start--》我是退出前回执的内容--- FAIL: TestPainc (0.00s) 48 | //panic: 异常退出 [recovered] 49 | //panic: 异常退出 50 | //goroutine 19 [running]: 51 | //testing.tRunner.func1(0xc0000a0100) 52 | 53 | //使用recover捕获panic抛出的异常 54 | func TestRecover(t *testing.T) { 55 | defer func() { 56 | if err := recover(); err != nil { 57 | //这里可以做"错误恢复" 58 | //常见的的"错误恢复",记录到打印日志里面,但是这样的修复方式是非常危险的,很容易出先僵尸进程,”Let it Crash“往往是我们恢复不确定性错误的最好方法 59 | log.Println("捕获到异常,手动处理异常") 60 | } 61 | }() 62 | fmt.Print("Start") 63 | panic(errors.New("异常退出")) 64 | } 65 | 66 | //运行结果 大家可以看到这里输出内容不是"异常退出"也没有打印栈信息了,因为我们手动处理了异常,但是这样做是对程序很危险的一种方式,懒点直接让程序崩溃反而更好,不然服务器炸了,不要让运维有甩锅给开发的机会 67 | //=== RUN TestRecover 68 | //Start2022/04/02 19:21:36 捕获到异常,手动处理异常信息 69 | //--- PASS: TestRecover (0.03s) 70 | //PASS 71 | -------------------------------------------------------------------------------- /go-18/client/package_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | cm "github.com/easierway/concurrent_map" //2.还可以导入第三方的包,这是导入一个开源项目的包,会自动git clone到本地 5 | "series" //1.这是导入自定义的包 路径,golang-examples\src\series 6 | "testing" 7 | ) 8 | 9 | //package(包) 10 | //1.基本复用模块单元 11 | //2.以首字母大写来表明可被包外代码访问 12 | //3.代码的package可以和所在目录不一致 13 | //4.同一目录里的Go代码package要保持一致 14 | //5.创建包前需要配置项目GOPATH路径 配置教程 https://www.freesion.com/article/4765574656/ 15 | // 注: 配置路径后,我发现go默认是src包下面的,所以项目的包创建在了 golang-examples\src\ 路径下 16 | 17 | func TestPackage(t *testing.T) { 18 | //调用golang-examples\src\series包里面的的Square函数 19 | t.Log(series.Square(1)) 20 | 21 | //小写的函数外部不能访问 22 | //t.Log(series.square(1)) 运行结果:undefined: series.square 23 | 24 | //使用远程的包函数 25 | m := cm.CreateConcurrentMap(99) 26 | m.Set(cm.StrKey("key"), 10) 27 | t.Log(m.Get(cm.StrKey("key"))) 28 | } 29 | 30 | //运行结果 31 | //=== RUN TestPackage 32 | //--- PASS: TestPackage (0.00s) 33 | //package_test.go:9: 1 34 | //PASS 35 | -------------------------------------------------------------------------------- /go-19/1.md: -------------------------------------------------------------------------------- 1 | ## 章节目录变更 2 | 3 | 所有使用到包的章节都放在src目录下面了 4 | 5 | 因为 go 编译器默认会在当前目录中查找src目录下package。 如果没有src目录,编译器就找不到相应的package 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /go-20/groutine_test.go: -------------------------------------------------------------------------------- 1 | package go_20 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | /* 10 | 11 | 协程机制 12 | 就是一种更轻量级的线程 13 | 其实你可以理解为java的多线程编程,只不过性能处理更加好 14 | 15 | java Thead 对比 go Groutine 16 | ## 创建时默认的stack(栈)的大小 17 | 1.jdk5以后java thread stack默认为1M 18 | 2.Groutine的stack初始大小为2k(这也就是为什么go语言比java更适合并发编程了) 19 | 20 | ## 和KSE(kernel space entity 系统线程)的对应关系 21 | 1.java thread是1:1 22 | 2.Groutine是M:N(多对多,所以go天生就是用来处理并发的) 23 | 24 | */ 25 | 26 | //测试 27 | func TestGroutine(t *testing.T) { 28 | for i := 0; i < 10; i++ { 29 | // 创建协程,如下写一个go就行了 30 | go func(i int) { 31 | fmt.Println(i) 32 | }(i) //这里i是值传递,每次都是复制一个,所以不会存在共享变量,需要像java加锁一样的问题,所以go天生并发 33 | } 34 | time.Sleep(time.Millisecond * 50) 35 | } 36 | 37 | /* 38 | 运行结果 结果顺序不一样,和java多线程一样理解就行了 39 | === RUN TestGroutine 40 | 2 41 | 0 42 | 5 43 | 3 44 | 4 45 | 1 46 | 7 47 | 6 48 | 8 49 | 9 50 | --- PASS: TestGroutine (0.05s) 51 | PASS 52 | */ 53 | -------------------------------------------------------------------------------- /go-21/share_mem_test.go: -------------------------------------------------------------------------------- 1 | package go_21 2 | 3 | import ( 4 | "sync" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | /* 10 | 共享内存并发机制 就类似于java里面的锁 11 | 12 | 都是些很简单的东西,直接看代码 13 | 14 | */ 15 | 16 | //不加锁的情况 17 | func TestCounter(t *testing.T) { 18 | count := 0 19 | for i := 0; i < 5000; i++ { 20 | go func() { 21 | count++ 22 | }() 23 | } 24 | time.Sleep(1 * time.Second) 25 | t.Logf("count=%d", count) 26 | } 27 | 28 | //运行结果 结果不是我们预想中的5000,发生了写入的问题,不是线程安全的 29 | //=== RUN TestCounter 30 | //--- PASS: TestCounter (1.02s) 31 | //share_mem_test.go:22: count=4936 32 | //PASS 33 | 34 | //加锁的情况 35 | func TestCounterThreadSafe(t *testing.T) { 36 | var mut = sync.Mutex{} 37 | count := 0 38 | for i := 0; i < 5000; i++ { 39 | go func() { 40 | defer func() { 41 | mut.Unlock() 42 | }() 43 | mut.Lock() 44 | count++ 45 | }() 46 | } 47 | time.Sleep(1 * time.Second) 48 | t.Logf("count=%d", count) 49 | } 50 | 51 | //运行结果 加锁之后结果是预想中的 52 | //=== RUN TestCounterThreadSafe 53 | //--- PASS: TestCounterThreadSafe (1.02s) 54 | //share_mem_test.go:47: count=5000 55 | //PASS 56 | 57 | //线程等待 58 | func TestCounterWaitGroup(t *testing.T) { 59 | var mut sync.Mutex 60 | var wg sync.WaitGroup 61 | count := 0 62 | for i := 0; i < 5000; i++ { 63 | wg.Add(1) 64 | go func() { 65 | defer func() { 66 | mut.Unlock() 67 | }() 68 | mut.Lock() 69 | count++ 70 | wg.Done() 71 | }() 72 | } 73 | wg.Wait() 74 | t.Logf("count=%d", count) 75 | } 76 | 77 | //运行结果 78 | //=== RUN TestCounterWaitGroup 79 | //--- PASS: TestCounterWaitGroup (0.03s) 80 | //share_mem_test.go:73: count=5000 81 | //PASS 82 | -------------------------------------------------------------------------------- /go-22/async_service_test.go: -------------------------------------------------------------------------------- 1 | package go_22 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | /* 10 | CSP并发机制 11 | 当成java的异步操作理解就行了,而CSP模式则是通过Channel进行通讯的,更松耦合一些 12 | 13 | Channel(管道,像理解消息队列的管道一样理解就行了) 14 | - Channel是Go中的一个核心类型,你可以把它看成一个管道,通过它并发核心单元就可以发送或者接收数据进行通讯 15 | - 容量(capacity)代表Channel容纳的最多的元素的数量,代表Channel的缓存的大小。 16 | - 如果没有设置容量,或者容量设置为0, 说明Channel没有缓存,只有sender和receiver都准备好了后它们的通讯 17 | 18 | ##如图:普通Channel 与 设置容量了Buffered Channels的区别 19 | 图左是普通Channel 图右是设置容量了Buffered Channels 20 | 图片路径:https://github.com/java-aodeng/golang-examples/blob/master/go-22/channel.png 21 | 22 | */ 23 | 24 | func service() string { 25 | time.Sleep(time.Millisecond * 50) 26 | return "Done" 27 | } 28 | 29 | func otherTask() { 30 | fmt.Println("working on something else") 31 | time.Sleep(time.Millisecond * 100) 32 | fmt.Println("Task is done.") 33 | } 34 | 35 | func TestService(t *testing.T) { 36 | fmt.Println(service()) 37 | otherTask() 38 | } 39 | 40 | //运行结果 可以看到结果是串行的,而且时间也等于两个函数总数相加 0.15s 41 | //=== RUN TestService 42 | //Done 43 | //working on something else 44 | //Task is done. 45 | //--- PASS: TestService (0.15s) 46 | //PASS 47 | 48 | func AsyncService() chan string { 49 | //使用make初始化普通Channel,不指定容量默认就是0 就是普通Channel 50 | retCh := make(chan string) 51 | go func() { 52 | ret := service() 53 | fmt.Println("returned result.") 54 | retCh <- ret 55 | fmt.Println("service exited.") 56 | }() 57 | return retCh 58 | } 59 | 60 | func AsyncService2() chan string { 61 | //使用make初始化Buffered Channels, 只要设置了容量,就是Buffered Channels 62 | retCh := make(chan string, 1) 63 | go func() { 64 | ret := service() 65 | fmt.Println("returned result.") 66 | retCh <- ret 67 | fmt.Println("service exited.") 68 | }() 69 | return retCh 70 | } 71 | 72 | //使用普通Channel 73 | func TestAsynService(t *testing.T) { 74 | retCh := AsyncService() 75 | otherTask() 76 | fmt.Println(<-retCh) 77 | } 78 | 79 | //运行结果 可以看到service exited.是最后返回结果的 80 | //=== RUN TestAsynService 81 | //working on something else 82 | //returned result. 83 | //Task is done. 84 | //Done 85 | //service exited. 86 | //--- PASS: TestAsynService (0.10s) 87 | //PASS 88 | 89 | //使用指定容量的Buffered Channels 90 | func TestAsynService2(t *testing.T) { 91 | retCh := AsyncService2() 92 | otherTask() 93 | fmt.Println(<-retCh) 94 | } 95 | 96 | //运行结果 可以看到在等待的时候同时执行了,service exited.没有阻塞 97 | //=== RUN TestAsynService 98 | //working on something else 99 | //returned result. 100 | //service exited. 101 | //Task is done. 102 | //Done 103 | //--- PASS: TestAsynService (0.10s) 104 | //PASS 105 | -------------------------------------------------------------------------------- /go-22/channel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/java-aodeng/golang-examples/b3f7e5a9cbdbbeff4e298cb4421c0a60ecfb012d/go-22/channel.png -------------------------------------------------------------------------------- /go-23/select_test.go: -------------------------------------------------------------------------------- 1 | package go_23 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | /* 10 | 多路由选择和超时 11 | */ 12 | 13 | func service() string { 14 | time.Sleep(time.Millisecond * 500) 15 | return "Done" 16 | } 17 | 18 | func AsyncService() chan string { 19 | //使用make初始化Buffered Channels, 只要设置了容量,就是Buffered Channels 20 | retCh := make(chan string, 1) 21 | go func() { 22 | ret := service() 23 | fmt.Println("returned result.") 24 | retCh <- ret 25 | fmt.Println("service exited.") 26 | }() 27 | return retCh 28 | } 29 | 30 | func TestSelect(t *testing.T) { 31 | //select 多渠道选择,语法与switch类似 32 | select { 33 | case ret := <-AsyncService(): 34 | t.Log(ret) 35 | //如果超时执行这个 36 | case <-time.After(time.Millisecond * 100): 37 | t.Errorf("time out") 38 | //default: 39 | // t.Log("执行完成") 40 | } 41 | } 42 | 43 | //运行结果 44 | //=== RUN TestSelect 45 | //--- FAIL: TestSelect (0.10s) 46 | //select_test.go:35: time out 47 | // 48 | //FAIL 49 | -------------------------------------------------------------------------------- /go-24/channel_close_test.go: -------------------------------------------------------------------------------- 1 | package go_24 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "testing" 7 | ) 8 | 9 | /* 10 | channel的关闭 11 | - 向关闭的channel发送数据,会导致panic 12 | - v,ok<-ch;ok为bool值,true表示正常接受,false表示通道关闭 13 | - 所有的channel接收者都会再channel关闭时,立刻从阻塞等待中返回且上述ok值为false,这个广播机制常被利用,进行向多个订阅者同时发送信息。如:退出信号。 14 | 15 | */ 16 | 17 | //数据提供者 向chan里面传0-9的数据 18 | func dataProduct(ch chan int, wg *sync.WaitGroup) { 19 | go func() { 20 | for i := 0; i < 10; i++ { 21 | ch <- i 22 | } 23 | //执行完了,关闭chan 24 | close(ch) 25 | //ch<-11 向关闭的chan发消息会抛异常 26 | //线程安全,不是本节重点,看不懂忽略 27 | wg.Done() 28 | }() 29 | } 30 | 31 | //数据消费者 取出chan里面0-9的数据 输出 32 | func dataReceiver(ch chan int, wg *sync.WaitGroup) { 33 | go func() { 34 | for { 35 | if data, ok := <-ch; ok { 36 | fmt.Println(data) 37 | } else { 38 | break 39 | } 40 | } 41 | wg.Done() 42 | }() 43 | } 44 | 45 | //测试 46 | func TestCloseChannel(t *testing.T) { 47 | var wg sync.WaitGroup 48 | //这里创建的是普通chan,不会存关闭chan有缓存的问题 49 | ch := make(chan int) 50 | 51 | //调用数据提供者 设置chan 52 | wg.Add(1) 53 | dataProduct(ch, &wg) 54 | 55 | //调用数据消费者 消费赋值了的chan 56 | wg.Add(1) 57 | dataReceiver(ch, &wg) 58 | 59 | //调用数据消费者 消费赋值了的chan 60 | wg.Add(1) 61 | dataReceiver(ch, &wg) 62 | wg.Wait() 63 | } 64 | 65 | /* 66 | 运行结果 可以看到输出顺序不一样,因为我们调用了两个消费者 还是很简单的东西 67 | === RUN TestCloseChannel 68 | 0 69 | 1 70 | 2 71 | 3 72 | 5 73 | 6 74 | 7 75 | 8 76 | 9 77 | 4 78 | --- PASS: TestCloseChannel (0.00s) 79 | PASS 80 | 81 | 82 | */ 83 | -------------------------------------------------------------------------------- /go-25/cancel_test.go: -------------------------------------------------------------------------------- 1 | package go_25 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func isCancelled(cancelChan chan struct{}) bool { 10 | select { 11 | case <-cancelChan: 12 | return true 13 | default: 14 | return false 15 | } 16 | } 17 | 18 | func cancel_1(cancelChan chan struct{}) { 19 | cancelChan <- struct{}{} 20 | } 21 | 22 | func cancel_2(cancelChan chan struct{}) { 23 | close(cancelChan) 24 | } 25 | 26 | func TestCancel(t *testing.T) { 27 | cancelChan := make(chan struct{}, 0) 28 | for i := 0; i < 5; i++ { 29 | go func(i int, cacelCh chan struct{}) { 30 | for { 31 | if isCancelled(cancelChan) { 32 | fmt.Println("isCancelled") 33 | break 34 | } 35 | fmt.Println("isSleep") 36 | time.Sleep(time.Millisecond * 1) 37 | } 38 | fmt.Println(i, "Cancelled") 39 | }(i, cancelChan) 40 | } 41 | //关闭渠道 关闭之后上面多线程里面会自动关闭循环 42 | cancel_2(cancelChan) 43 | 44 | time.Sleep(time.Second * 10) 45 | } 46 | 47 | /* 48 | 运行结果 执行cancel_2方法后关闭了渠道 多线程for循环里面就立马关闭了循环,注释掉cancel_2再执行,会for循环打印isSleep直到10秒后退出 49 | === RUN TestCancel 50 | isCancelled 51 | 3 Cancelled 52 | isCancelled 53 | 4 Cancelled 54 | isCancelled 55 | 1 Cancelled 56 | isCancelled 57 | 2 Cancelled 58 | isCancelled 59 | 0 Cancelled 60 | --- PASS: TestCancel (1.00s) 61 | PASS 62 | 63 | 64 | Process finished with the exit code 0 65 | 66 | */ 67 | -------------------------------------------------------------------------------- /go-26/cancel_by_context_test.go: -------------------------------------------------------------------------------- 1 | package go_25 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | /* 11 | Context 12 | 关联任务的取消,就是用来当前线程被取消,相关联的子线程也会被取消的场景 13 | - 根Context:通过context.Background()创建 14 | - 子Context:context.WithCancel(parentContext)创建 15 | ctx,cancel=context.WithCancel(context.Background()) 16 | - 当前Context被取消时,基于他的子context都会被取消 17 | - 接受取消通知<-ctx.Done() 18 | 19 | */ 20 | func isCancelled(ctx context.Context) bool { 21 | select { 22 | case <-ctx.Done(): 23 | return true 24 | default: 25 | return false 26 | } 27 | } 28 | 29 | func TestCancel(t *testing.T) { 30 | ctx, cancel := context.WithCancel(context.Background()) 31 | for i := 0; i < 5; i++ { 32 | go func(i int, ctx context.Context) { 33 | for { 34 | if isCancelled(ctx) { 35 | fmt.Println("isCancelled") 36 | break 37 | } 38 | fmt.Println("isSleep") 39 | time.Sleep(time.Millisecond * 1) 40 | } 41 | fmt.Println(i, "Cancelled") 42 | }(i, ctx) 43 | } 44 | //关闭渠道 关闭之后上面多线程里面会自动关闭循环 45 | cancel() 46 | 47 | time.Sleep(time.Second * 10) 48 | } 49 | 50 | /* 51 | 运行结果 执行cancel_2方法后关闭了渠道 多线程for循环里面就立马关闭了循环,注释掉cancel_2再执行,会for循环打印isSleep直到10秒后退出 52 | === RUN TestCancel 53 | isCancelled 54 | 3 Cancelled 55 | isCancelled 56 | 4 Cancelled 57 | isCancelled 58 | 1 Cancelled 59 | isCancelled 60 | 2 Cancelled 61 | isCancelled 62 | 0 Cancelled 63 | --- PASS: TestCancel (1.00s) 64 | PASS 65 | 66 | 67 | Process finished with the exit code 0 68 | 69 | */ 70 | -------------------------------------------------------------------------------- /go-27/once_test.go: -------------------------------------------------------------------------------- 1 | package go_27 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "testing" 7 | "unsafe" 8 | ) 9 | 10 | /* 11 | 其实就是java里面的单例模式,一样理解即可 12 | go语言里面有个once方法只会执行一次,使用这个实现线程安全的懒汉单例模式 13 | */ 14 | 15 | type Singleton struct { 16 | data string 17 | } 18 | 19 | var sigleInstance *Singleton 20 | var once sync.Once 21 | 22 | func GetSingletonObj() *Singleton { 23 | 24 | //这个方法只会执行一次,不需要像java一样非空判断,第一次是肯定会创建对象的,且只会执行一次 25 | once.Do(func() { 26 | fmt.Println("Create Obj") 27 | sigleInstance = new(Singleton) 28 | }) 29 | return sigleInstance 30 | } 31 | 32 | func TestGetSingletonObj(t *testing.T) { 33 | var wg sync.WaitGroup 34 | for i := 0; i < 10; i++ { 35 | wg.Add(1) 36 | go func() { 37 | obj := GetSingletonObj() 38 | fmt.Printf("对象引用地址:%X\n", unsafe.Pointer(obj)) 39 | wg.Done() 40 | }() 41 | } 42 | wg.Wait() 43 | } 44 | 45 | /* 46 | 运行结果:可以看到对象只创建了一次,后面都是获取的同一个对象引用,与java单例模式一样理解即可 47 | === RUN TestGetSingletonObj 48 | Create Obj 49 | 对象引用地址:C000030010 50 | 对象引用地址:C000030010 51 | 对象引用地址:C000030010 52 | 对象引用地址:C000030010 53 | 对象引用地址:C000030010 54 | 对象引用地址:C000030010 55 | 对象引用地址:C000030010 56 | 对象引用地址:C000030010 57 | 对象引用地址:C000030010 58 | 对象引用地址:C000030010 59 | --- PASS: TestGetSingletonObj (0.00s) 60 | PASS 61 | */ 62 | -------------------------------------------------------------------------------- /go-28/first_response_test.go: -------------------------------------------------------------------------------- 1 | package go_28 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | /* 11 | 仅需任意任务完成 12 | 13 | 举例:我们搜索一个问题,同时触发google,百度,必应三个程序去搜索,只要有一个程序搜索到结果,就可以返回结果了 14 | 15 | */ 16 | 17 | //一个简单的函数,打印传入的id 18 | func runTask(id int) string { 19 | time.Sleep(10 * time.Millisecond) 20 | return fmt.Sprintf("当前返回id为%d", id) 21 | } 22 | 23 | //返回第一个传入的数据id 24 | func FirstResponse() string { 25 | numOfRunner := 10 26 | //这里创建一个Buffered Channels,防止协程阻塞,很重要 27 | ch := make(chan string, numOfRunner) 28 | for i := 0; i < numOfRunner; i++ { 29 | go func(i int) { 30 | ret := runTask(i) 31 | ch <- ret 32 | }(i) 33 | } 34 | return <-ch 35 | } 36 | 37 | func TestFirsResponse(t *testing.T) { 38 | fmt.Println("Before", runtime.NumGoroutine()) 39 | fmt.Println(FirstResponse()) 40 | time.Sleep(time.Second * 1) 41 | fmt.Println("After", runtime.NumGoroutine()) 42 | } 43 | 44 | /*运行结果 返回id会每次不相同,这是因为go的协程调用机制的顺序不同 45 | === RUN TestFirsResponse 46 | Before 2 47 | 当前返回id为2 48 | After 2 49 | --- PASS: TestFirsResponse (1.02s) 50 | PASS 51 | */ 52 | -------------------------------------------------------------------------------- /go-29/all_done_test.go: -------------------------------------------------------------------------------- 1 | package go_29 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | /* 11 | 所有任务完成 12 | 13 | 与上一章刚好相反,要程序所有协程执行完了,才返回结果 14 | */ 15 | 16 | //一个简单的函数,打印传入的id 17 | func runTask(id int) string { 18 | time.Sleep(10 * time.Millisecond) 19 | return fmt.Sprintf("当前返回id为%d", id) 20 | } 21 | 22 | //所有任务完成才返回 23 | func AllResponse() string { 24 | numOfRunner := 10 25 | //这里创建一个Buffered Channels,防止协程阻塞,很重要 26 | ch := make(chan string, numOfRunner) 27 | for i := 0; i < numOfRunner; i++ { 28 | go func(i int) { 29 | ret := runTask(i) 30 | ch <- ret 31 | }(i) 32 | } 33 | 34 | finalRet := "" 35 | for j := 0; j < numOfRunner; j++ { 36 | finalRet += <-ch + "\n" 37 | } 38 | 39 | return finalRet 40 | } 41 | 42 | func TestFirsResponse(t *testing.T) { 43 | fmt.Println("Before", runtime.NumGoroutine()) 44 | fmt.Println(AllResponse()) 45 | time.Sleep(time.Second * 1) 46 | fmt.Println("After", runtime.NumGoroutine()) 47 | } 48 | 49 | /* 50 | 运行结果 51 | === RUN TestFirsResponse 52 | Before 2 53 | 当前返回id为9 54 | 当前返回id为7 55 | 当前返回id为1 56 | 当前返回id为8 57 | 当前返回id为2 58 | 当前返回id为5 59 | 当前返回id为4 60 | 当前返回id为6 61 | 当前返回id为0 62 | 当前返回id为3 63 | 64 | After 2 65 | --- PASS: TestFirsResponse (1.01s) 66 | PASS 67 | */ 68 | -------------------------------------------------------------------------------- /go-30/obj_pool_test.go: -------------------------------------------------------------------------------- 1 | package go_30 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | /* 11 | 对象池 12 | 13 | go语言对象池 可以利用Buffered Channels来实现 14 | 15 | */ 16 | 17 | //定义一个对象 18 | type ReusableObj struct { 19 | } 20 | 21 | //用于缓冲可重用对象 22 | type ObjPool struct { 23 | bufChan chan *ReusableObj 24 | } 25 | 26 | //创建一个对象池 27 | func NewObjPool(numOfObj int) *ObjPool { 28 | objPool := ObjPool{} 29 | //创建的Buffered Channels 指定容量numOfObj 30 | objPool.bufChan = make(chan *ReusableObj, numOfObj) 31 | for i := 0; i < numOfObj; i++ { 32 | objPool.bufChan <- &ReusableObj{} 33 | } 34 | return &objPool 35 | } 36 | 37 | //获取对象 38 | func (p *ObjPool) GetObj(timeout time.Duration) (*ReusableObj, error) { 39 | select { 40 | case ret := <-p.bufChan: 41 | return ret, nil 42 | case <-time.After(timeout): //超时控制 43 | return nil, errors.New("超时") 44 | } 45 | } 46 | 47 | //释放对象 48 | func (p *ObjPool) ReleaseObj(obj *ReusableObj) error { 49 | select { 50 | case p.bufChan <- obj: 51 | return nil 52 | default: 53 | return errors.New("overflow") 54 | 55 | } 56 | } 57 | 58 | func TestObjPool(t *testing.T) { 59 | //创建一个对象池子 60 | pool := NewObjPool(10) 61 | for i := 0; i < 11; i++ { 62 | if v, err := pool.GetObj(time.Second * 1); err != nil { 63 | t.Error(err) 64 | } else { 65 | fmt.Printf("%T\n", v) 66 | if err := pool.ReleaseObj(v); err != nil { 67 | t.Error(err) 68 | } 69 | } 70 | } 71 | fmt.Println("Done") 72 | } 73 | 74 | /*运行结果 75 | === RUN TestObjPool 76 | *go_30.ReusableObj 77 | *go_30.ReusableObj 78 | *go_30.ReusableObj 79 | *go_30.ReusableObj 80 | *go_30.ReusableObj 81 | *go_30.ReusableObj 82 | *go_30.ReusableObj 83 | *go_30.ReusableObj 84 | *go_30.ReusableObj 85 | *go_30.ReusableObj 86 | *go_30.ReusableObj 87 | Done 88 | --- PASS: TestObjPool (0.00s) 89 | PASS 90 | 91 | 92 | Process finished with the exit code 0 93 | 94 | */ 95 | -------------------------------------------------------------------------------- /go-31/sync_pool_test.go: -------------------------------------------------------------------------------- 1 | package go_31 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "sync" 7 | "testing" 8 | ) 9 | 10 | /* 11 | sync.pool对象缓存 12 | 13 | sync.Pool对象获取 14 | - 尝试从私有对象获取 15 | - 私有对象不存在,尝试从当前Processor的共享池获取 16 | - 如果当前Processor共享池是空的,那么就尝试去其他Processor的共享池获取 17 | - 如果所有池都是空的,最后就用用户指定的new函数产生一个新的对象返回 18 | 19 | sync.Pool对象的生命周期 20 | - GC会清楚sync.pool缓存的对象 21 | - 对象的缓存有效期为下一次GC之前 22 | 23 | sync.Pool总结 24 | - 使用与通过复用,降低复杂对象的创建和GC代价 25 | - 协程安全,会有锁的开销 26 | - 生命周期受GC影响,不适合于做连接池等,需要自己管理生命周期的资源池化 27 | */ 28 | 29 | func TestSyncPool(t *testing.T) { 30 | pool := &sync.Pool{ 31 | New: func() interface{} { 32 | fmt.Println("创建一个对象.") 33 | return 100 34 | }, 35 | } 36 | v := pool.Get().(int) 37 | fmt.Println("得到的对象", v) 38 | //手动添加值 39 | pool.Put(1) 40 | //GC会清除sync.pool中缓存的对象 41 | runtime.GC() 42 | v1, _ := pool.Get().(int) 43 | fmt.Println("v1=", v1) 44 | } 45 | 46 | /*TestSyncPool运行结果 可以看到GC之前put的1没有输出,被清除了 47 | === RUN TestSyncPool 48 | 创建一个对象. 49 | 得到的对象 100 50 | 创建一个对象. 51 | v1= 100 52 | --- PASS: TestSyncPool (0.00s) 53 | PASS 54 | */ 55 | 56 | func TestSyncPoolInMultiGroutine(t *testing.T) { 57 | pool := &sync.Pool{ 58 | New: func() interface{} { 59 | fmt.Println("创建一个对象.") 60 | return 10 61 | }, 62 | } 63 | 64 | pool.Put(100) 65 | pool.Put(100) 66 | pool.Put(100) 67 | 68 | var wg sync.WaitGroup 69 | for i := 0; i < 10; i++ { 70 | wg.Add(1) 71 | go func(id int) { 72 | fmt.Println(pool.Get()) 73 | wg.Done() 74 | }(i) 75 | } 76 | wg.Wait() 77 | } 78 | 79 | /* 80 | 运行结果 可以看到10次里面三次都是取的100,7次是创建的10 81 | === RUN TestSyncPoolInMultiGroutine 82 | 100 83 | 创建一个对象. 84 | 10 85 | 100 86 | 创建一个对象. 87 | 10 88 | 创建一个对象. 89 | 创建一个对象. 90 | 10 91 | 创建一个对象. 92 | 创建一个对象. 93 | 10 94 | 创建一个对象. 95 | 10 96 | 100 97 | 10 98 | 10 99 | */ 100 | -------------------------------------------------------------------------------- /go-32/function_test.go: -------------------------------------------------------------------------------- 1 | package go_32 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | /* 9 | 内置单元测试框架 10 | go语言创建单元测试文件,就是文件命名加个_test,测试的入口方法Test开头就行了,比java简洁多了 11 | 12 | - Fail,Error:该测试失败,该测试继续,其他测试继续执行 13 | - FailNow,Fatal:该测试失败,该测试中止,其他测试继续执行 14 | 15 | */ 16 | 17 | func TestErrorInCode(t *testing.T) { 18 | fmt.Println("Start") 19 | t.Error("Error") 20 | fmt.Println("End") 21 | } 22 | 23 | func TestFailInCode(t *testing.T) { 24 | fmt.Println("Start") 25 | t.Fatal("Error") 26 | fmt.Println("End") 27 | } 28 | 29 | /* 30 | 以上两个方法同时运行结果:可以看到区别和上面描述一样 31 | === RUN TestErrorInCode 32 | Start 33 | End 34 | --- FAIL: TestErrorInCode (0.00s) 35 | function_test.go:17: Error 36 | === RUN TestFailInCode 37 | Start 38 | --- FAIL: TestFailInCode (0.00s) 39 | function_test.go:23: Error 40 | FAIL 41 | 42 | */ 43 | -------------------------------------------------------------------------------- /go-33/benchmark_test.go: -------------------------------------------------------------------------------- 1 | package go_33 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | ) 7 | 8 | /* 9 | Benchmark 10 | 用于一些性能测试中,方法名字以Benchmark为前缀 11 | 参数使用testing.B 12 | 13 | func BenchmarkConcatStringByBytesBuffer(b *testing.B) { 14 | //与性能测试无关代码 15 | b.ResetTimer() 16 | for i := 0; i < b.N; i++ { 17 | //测试代码 18 | } 19 | b.StopTimer() 20 | //与性能测试无关代码 21 | } 22 | 23 | */ 24 | 25 | func BenchmarkConcatStringByBytesBuffer(b *testing.B) { 26 | elems := []string{"1", "2", "3", "4", "5"} 27 | b.ResetTimer() 28 | for i := 0; i < b.N; i++ { 29 | var buf bytes.Buffer 30 | 31 | for _, elem := range elems { 32 | buf.WriteString(elem) 33 | 34 | } 35 | } 36 | b.StopTimer() 37 | 38 | } 39 | 40 | /* 41 | //运行结果 42 | goos: windows 43 | goarch: amd64 44 | BenchmarkConcatStringByBytesBuffer-4 10000000 142 ns/op 45 | PASS*/ 46 | -------------------------------------------------------------------------------- /go-34/bdd_test.go: -------------------------------------------------------------------------------- 1 | package go_34 2 | 3 | /* 4 | Behavior Driven Development 5 | 6 | BDD in Go 7 | 开源地址:github.com/smartystreets/goconvey 8 | 9 | 安装 10 | $ go get github.com/smartystreets/goconvey 11 | 12 | 启动 WEB UI 13 | $ $GOPATH/bin/goconvey 14 | 15 | 这里运行需要go的1.14版本,不然会出现 errors.Is的问题 16 | */ 17 | import ( 18 | . "github.com/smartystreets/goconvey/convey" 19 | "testing" 20 | ) 21 | 22 | func TestSpec(t *testing.T) { 23 | 24 | // Only pass t into top-level Convey calls 25 | Convey("Given 2 even numbers", t, func() { 26 | a := 3 27 | b := 4 28 | 29 | Convey("When add the two numbers", func() { 30 | c := a + b 31 | 32 | Convey("Then the result is still even", func() { 33 | So(c%2, ShouldEqual, 0) 34 | }) 35 | }) 36 | }) 37 | } 38 | -------------------------------------------------------------------------------- /go-35/reflect_test.go: -------------------------------------------------------------------------------- 1 | package go_35 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | /* 10 | 反射编程 11 | 12 | reflect.TypeOf reflect.ValueOf 13 | - reflect.TypeOf 返回类型(reflect.Type) 14 | - reflect.ValueOf 返回值(reflect.Value) 15 | - 可以从reflect.Value获得类型 16 | - 通过kind来判断类型 17 | */ 18 | 19 | func TestTypeAndValue(t *testing.T) { 20 | var f int64 = 10 21 | t.Log(reflect.TypeOf(f), reflect.ValueOf(f)) 22 | t.Log(reflect.ValueOf(f).Type()) 23 | } 24 | 25 | /* 26 | 运行结果: 27 | === RUN TestTypeAndValue 28 | reflect_test.go:21: int64 10 29 | reflect_test.go:22: int64 30 | --- PASS: TestTypeAndValue (0.00s) 31 | PASS 32 | */ 33 | 34 | func CheckType(v interface{}) { 35 | t := reflect.TypeOf(v) 36 | switch t.Kind() { 37 | case reflect.Float32, reflect.Float64: 38 | fmt.Println("Float") 39 | case reflect.Int, reflect.Int32, reflect.Int64: 40 | fmt.Println("Integer") 41 | default: 42 | fmt.Println("Unknown", t) 43 | } 44 | } 45 | 46 | //用反射获得类型 47 | func TestBasicType(t *testing.T) { 48 | var f float64 = 12 49 | CheckType(&f) 50 | 51 | } 52 | 53 | /* 54 | 运行结果 55 | === RUN TestBasicType 56 | Unknown *float64 57 | --- PASS: TestBasicType (0.00s) 58 | PASS 59 | */ 60 | 61 | func TestDeepEqual(t *testing.T) { 62 | a := map[int]string{1: "one", 2: "two", 3: "three"} 63 | b := map[int]string{1: "one", 2: "two", 3: "three"} 64 | // t.Log(a == b) 65 | t.Log("a==b?", reflect.DeepEqual(a, b)) 66 | 67 | s1 := []int{1, 2, 3} 68 | s2 := []int{1, 2, 3} 69 | s3 := []int{2, 3, 1} 70 | 71 | t.Log("s1 == s2?", reflect.DeepEqual(s1, s2)) 72 | t.Log("s1 == s3?", reflect.DeepEqual(s1, s3)) 73 | 74 | c1 := Customer{"1", "Mike", 40} 75 | c2 := Customer{"1", "Mike", 40} 76 | fmt.Println(c1 == c2) 77 | fmt.Println(reflect.DeepEqual(c1, c2)) 78 | } 79 | 80 | /* 81 | 运行结果: 82 | === RUN TestDeepEqual 83 | reflect_test.go:47: a==b? true 84 | reflect_test.go:53: s1 == s2? true 85 | reflect_test.go:54: s1 == s3? false 86 | true 87 | true 88 | --- PASS: TestDeepEqual (0.00s) 89 | PASS 90 | */ 91 | 92 | type Employee struct { 93 | EmployeeID string 94 | Name string `format:"normal"` 95 | Age int 96 | } 97 | 98 | func (e *Employee) UpdateAge(newVal int) { 99 | e.Age = newVal 100 | } 101 | 102 | type Customer struct { 103 | CookieID string 104 | Name string 105 | Age int 106 | } 107 | 108 | func TestInvokeByName(t *testing.T) { 109 | e := &Employee{"1", "Mike", 30} 110 | //按名字获取成员 111 | t.Logf("Name: value(%[1]v), Type(%[1]T) ", reflect.ValueOf(*e).FieldByName("Name")) 112 | if nameField, ok := reflect.TypeOf(*e).FieldByName("Name"); !ok { 113 | t.Error("Failed to get 'Name' field.") 114 | } else { 115 | t.Log("Tag:format", nameField.Tag.Get("format")) 116 | } 117 | reflect.ValueOf(e).MethodByName("UpdateAge"). 118 | Call([]reflect.Value{reflect.ValueOf(1)}) 119 | t.Log("Updated Age:", e) 120 | } 121 | 122 | /* 123 | 运行结果 124 | === RUN TestInvokeByName 125 | reflect_test.go:81: Name: value(Mike), Type(reflect.Value) 126 | reflect_test.go:85: Tag:format normal 127 | reflect_test.go:89: Updated Age: &{1 Mike 1} 128 | --- PASS: TestInvokeByName (0.00s) 129 | PASS 130 | */ 131 | -------------------------------------------------------------------------------- /go-36/flexible_reflect_test.go: -------------------------------------------------------------------------------- 1 | package go_36 2 | 3 | import ( 4 | "errors" 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | /* 10 | 万能程序(原理都是利用go反射的特性,就和java差球不多,动态编程而已,理解了就是有手就行,看不懂这边建议直接放弃) 11 | 12 | DeepEqual 13 | - 比较切片和map 14 | 15 | 万能赋值 16 | - 给两个不同的对象,但是相同属性的字段同时赋值 17 | 18 | 两个万能程序示例如下: 19 | */ 20 | 21 | /* 22 | DeepEqual =====================万能程序1=========================== 23 | - 比较切片和map 24 | */ 25 | func TestDeepEqual(t *testing.T) { 26 | a := map[int]string{1: "one", 2: "two", 3: "three"} 27 | b := map[int]string{1: "one", 2: "two", 3: "three"} 28 | //t.Log(a == b) //运行这行会报错,go语言不能直接比较 invalid operation: a == b (map can only be compared to nil) 29 | t.Log(reflect.DeepEqual(a, b)) 30 | 31 | s1 := []int{1, 2, 3} 32 | s2 := []int{1, 2, 3} 33 | s3 := []int{2, 3, 1} 34 | t.Log("s1 == s2?", reflect.DeepEqual(s1, s2)) 35 | t.Log("s1 == s3?", reflect.DeepEqual(s1, s3)) 36 | } 37 | 38 | /* 运行结果:可以看到我们可以使用DeepEqual比较两个数组是否相等 39 | === RUN TestDeepEqual 40 | flexible_reflect_test.go:21: true 41 | flexible_reflect_test.go:26: s1 == s2? true 42 | flexible_reflect_test.go:27: s1 == s3? false 43 | --- PASS: TestDeepEqual (0.00s) 44 | PASS 45 | */ 46 | 47 | /* 48 | =====================万能程序2=========================== 49 | 万能赋值 50 | - 给两个不同的对象,但是相同属性的字段同时赋值。 51 | */ 52 | 53 | //下面两个对象:相同属性为:Name,Age 54 | type Employee struct { 55 | EmployeeID string 56 | Name string `format:"normal"` 57 | Age int 58 | } 59 | 60 | type Customer struct { 61 | CookieID string 62 | Name string 63 | Age int 64 | } 65 | 66 | //给不同对象,相同属性赋值 67 | //st参数为传入的类型,settings为传入的值 68 | func fillBySettings(st interface{}, settings map[string]interface{}) error { 69 | 70 | // func (v Value) Elem() Value 71 | // Elem returns the value that the interface v contains or that the pointer v points to. 72 | // It panics if v's Kind is not Interface or Ptr. 73 | // It returns the zero Value if v is nil. 74 | 75 | if reflect.TypeOf(st).Kind() != reflect.Ptr { //判断参数是不是一个指针 76 | return errors.New("the first param should be a pointer to the struct type.") 77 | } 78 | // Elem() 获取指针指向的值 79 | if reflect.TypeOf(st).Elem().Kind() != reflect.Struct { //判断参数是不是一个结构体 80 | return errors.New("the first param should be a pointer to the struct type.") 81 | } 82 | 83 | if settings == nil { 84 | return errors.New("settings is nil.") 85 | } 86 | 87 | var ( 88 | field reflect.StructField 89 | ok bool 90 | ) 91 | 92 | //这里其实就是循环遍历 93 | for k, v := range settings { 94 | if field, ok = (reflect.ValueOf(st)).Elem().Type().FieldByName(k); !ok { 95 | continue 96 | } 97 | //如果传入的对象的属性 和值的key相同就赋值 98 | if field.Type == reflect.TypeOf(v) { 99 | vstr := reflect.ValueOf(st) 100 | vstr = vstr.Elem() 101 | vstr.FieldByName(k).Set(reflect.ValueOf(v)) 102 | } 103 | 104 | } 105 | return nil 106 | } 107 | 108 | func TestFillNameAndAge(t *testing.T) { 109 | //定义一个数组 110 | settings := map[string]interface{}{"Name": "Mike", "Age": 30} 111 | e := Employee{} 112 | if err := fillBySettings(&e, settings); err != nil { 113 | t.Fatal(err) 114 | } 115 | t.Log(e) 116 | c := new(Customer) 117 | if err := fillBySettings(c, settings); err != nil { 118 | t.Fatal(err) 119 | } 120 | t.Log(*c) 121 | } 122 | 123 | /* 124 | 运行结果:两个对象,相同的属性赋值相同了,这样有的场景下,能节省很多代码 125 | === RUN TestFillNameAndAge 126 | flexible_reflect_test.go:114: { Mike 30} 127 | flexible_reflect_test.go:119: { Mike 30} 128 | --- PASS: TestFillNameAndAge (0.00s) 129 | PASS 130 | 131 | */ 132 | -------------------------------------------------------------------------------- /go-37/unsafe_test.go: -------------------------------------------------------------------------------- 1 | package go_37 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "sync/atomic" 7 | "testing" 8 | "time" 9 | "unsafe" 10 | ) 11 | 12 | /* 13 | 不安全编程 14 | 15 | - go语言是不持支强制类型转换的 16 | */ 17 | 18 | func TestUnsafe(t *testing.T) { 19 | i := 10 20 | f := *(*float64)(unsafe.Pointer(&i)) 21 | t.Log(unsafe.Pointer(&i)) 22 | t.Log(f) 23 | } 24 | 25 | /* 运行结果,可以看到一个10强制类型转换后值变成了5e-323,所有go是不能这样写的,没java方便 26 | === RUN TestUnsafe 27 | unsafe_test.go:17: 0xc00000a370 28 | unsafe_test.go:18: 5e-323 29 | --- PASS: TestUnsafe (0.00s) 30 | PASS 31 | */ 32 | 33 | //原子类型操作 34 | func TestAtomic(t *testing.T) { 35 | var shareBufPtr unsafe.Pointer 36 | writeDataFn := func() { 37 | data := []int{} 38 | for i := 0; i < 100; i++ { 39 | data = append(data, i) 40 | } 41 | atomic.StorePointer(&shareBufPtr, unsafe.Pointer(&data)) 42 | } 43 | readDataFn := func() { 44 | data := atomic.LoadPointer(&shareBufPtr) 45 | fmt.Println(data, *(*[]int)(data)) 46 | } 47 | var wg sync.WaitGroup 48 | writeDataFn() 49 | for i := 0; i < 10; i++ { 50 | wg.Add(1) 51 | go func() { 52 | for i := 0; i < 10; i++ { 53 | writeDataFn() 54 | time.Sleep(time.Microsecond * 100) 55 | } 56 | wg.Done() 57 | }() 58 | wg.Add(1) 59 | go func() { 60 | for i := 0; i < 10; i++ { 61 | readDataFn() 62 | time.Sleep(time.Microsecond * 100) 63 | } 64 | wg.Done() 65 | }() 66 | } 67 | wg.Wait() 68 | } 69 | -------------------------------------------------------------------------------- /go-38/1.md: -------------------------------------------------------------------------------- 1 | ## 章节目录变更 2 | 3 | 所有使用到包的章节都放在src目录下面了 4 | 5 | 因为 go 编译器默认会在当前目录中查找src目录下package。 如果没有src目录,编译器就找不到相应的package 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /go-test-code/1.md: -------------------------------------------------------------------------------- 1 | # go-test-code 2 | >练习代码 code_test.go -------------------------------------------------------------------------------- /go-test-code/code_test.go: -------------------------------------------------------------------------------- 1 | package go_test_code 2 | 3 | import ( 4 | //自定义包名aodeng 5 | aodeng "fmt" 6 | "math" 7 | "os" 8 | "runtime" 9 | "testing" 10 | ) 11 | 12 | //类型转换 13 | func TestCode(t *testing.T) { 14 | a := 5.0 15 | //类型 B 的值 = 类型 B(类型 A 的值) 16 | b := int(a) 17 | aodeng.Print(b) 18 | } 19 | 20 | //常量 21 | func TestCode2(t *testing.T) { 22 | const Pi = 3.14159 23 | //显式类型定义: 24 | const b1 string = "abc" 25 | //隐式类型定义: 26 | const b2 = "abc" 27 | t.Log(Pi) 28 | t.Log(b1) 29 | t.Log(b2) 30 | } 31 | 32 | //全局变量 33 | var ( 34 | a int 35 | b bool 36 | c string 37 | ) 38 | 39 | //下面是如何通过runtime包在运行时获取所在的操作系统类型,以及如何通过 os 包中的函数 os.Getenv() 来获取环境变量中的值,并保存到 string 类型的局部变量 path 中 40 | func TestCode3(t *testing.T) { 41 | var goos string = runtime.GOOS 42 | aodeng.Printf("The operating system is: %s\n", goos) 43 | path := os.Getenv("PATH") 44 | aodeng.Printf("Path is %s\n", path) 45 | } 46 | 47 | //变量除了可以在全局声明中初始化,也可以在 init 函数中初始化。这是一类非常特殊的函数,它不能够被人为调用,而是在每个包完成初始化后自动执行,并且执行优先级比 main 函数高。 48 | //每个源文件都只能包含一个 init 函数。初始化总是以单线程执行,并且按照包的依赖关系顺序执行。 49 | //一个可能的用途是在开始执行程序之前对数据进行检验或修复,以保证程序状态的正确性 50 | var Pi float64 51 | 52 | func init() { 53 | Pi = 4 * math.Atan(1) 54 | } 55 | func TestCode4(t *testing.T) { 56 | var twoPi = 2 * Pi 57 | aodeng.Print("2*Pi:", twoPi) 58 | } 59 | -------------------------------------------------------------------------------- /src/go-19/module_package/get_remote_pack_test.go: -------------------------------------------------------------------------------- 1 | package module_package 2 | 3 | import ( 4 | cm "github.com/easierway/concurrent_map" 5 | "testing" 6 | ) 7 | 8 | //## 章节目录变更 9 | 10 | //所有使用到包的章节都放在src目录下面了 11 | 12 | //因为 go 编译器默认会在当前目录中查找src目录下package。 如果没有src目录,编译器就找不到相应的package 13 | 14 | /* 15 | ---->理论部分 16 | 依赖管理 17 | Go未解决的依赖问题 18 | 1.同一环境下,不同项目使用同一包的不同版本 19 | 2.无法管理对包的特定版本的依赖 20 | 21 | vendor路径 22 | 随着Go 1.5release版本的发布,vendor目录被添加到除GOPAHR和GOROOT之外的依赖目录查找的解决方案 23 | 在Go 1.6之前,你需要手动的设置环境变量 24 | 25 | 查找依赖包路径的解决方案如下: 26 | 1.当前包的vendor目录 27 | 2.向上目录查找,直到找到src下的vendor目录 28 | 3.GOPATH下面查找依赖包 29 | 4.GOROOT下面查找依赖包 30 | 31 | 常用的依赖管理工具 32 | dodep:https://github.com/tools/godep 33 | glide:https://github.com/Masterminds/glide 34 | dep:https://github.com/golang/dep 35 | 36 | ---->操作部分 37 | window安装glide教程: https://www.cnblogs.com/nickchou/p/8955180.html 38 | 安装成功后,我们把src/github.com/easierway包的源文件删除,运行下面代码会报错找不到包 39 | 然后在go-19/module_package目录下执行 40 | 41 | ##初始化包管理 42 | glide init 43 | ##下载项目依赖 44 | glide install 45 | 46 | 会重新下载包源文件到项目go-19/module_package/vendor目录下,glide.yaml文件就类似于maven文件,版本管理 47 | 48 | 遇到的问题:解决go build不去vendor下查找包的问题: https://www.jb51.net/article/202458.htm 49 | 问题总结:go 编译器默认会在当前目录中查找src目录下package。如果没有src目录,编译器就找不到相应的package 50 | 51 | 52 | */ 53 | func TestConcurrentMap(t *testing.T) { 54 | 55 | m := cm.CreateConcurrentMap(99) 56 | m.Set(cm.StrKey("key"), 10) 57 | t.Log(m.Get(cm.StrKey("key"))) 58 | } 59 | 60 | //运行结果 61 | //=== RUN TestConcurrentMap 62 | //--- PASS: TestConcurrentMap (0.00s) 63 | //get_remote_pack_test.go:48: 10 true 64 | //PASS 65 | -------------------------------------------------------------------------------- /src/go-19/module_package/glide.lock: -------------------------------------------------------------------------------- 1 | hash: ccb2961c4fa3b33a4a6676fdb31342317663f95a81b4db178e5e6bfdee5d0974 2 | updated: 2022-04-04T18:12:51.4090812+08:00 3 | imports: [] 4 | testImports: 5 | - name: github.com/easierway/concurrent_map 6 | version: 7073b0dd7e9577513a78225491cb4a68e6d62a86 7 | -------------------------------------------------------------------------------- /src/go-19/module_package/glide.yaml: -------------------------------------------------------------------------------- 1 | package: go-19/module_package/get_remote_pack_test.go 2 | import: [] 3 | testImport: 4 | - package: github.com/easierway/concurrent_map 5 | version: ^1.0.0 6 | -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/README.md: -------------------------------------------------------------------------------- 1 | # ConcurrentMap for GO 2 | ## The better performance thread-safe map in GO 3 | 4 | After v1.9, normally, programmers have two options for thread-safe map. One is to build the thread-safe solution with syn.RWMutex. But, in many cases, especially, in the case the number of CPU cores is larger than 2, this option's performance is quite poor. 5 | 6 | Another is to use the sync.map, which has been added to the sync package from v.1.9. Unfortunately, sync.map can not work well for all the cases, especially, the case of multi-threads writing. For more info, please, check the great video https://www.youtube.com/watch?v=C1EtfDnsdDs. 7 | 8 | This project is to provide a thread-safe map which is Java ConcurrentMap's GO version. From the following benchmark you can see it is better in the multi-thread writing cases. 9 | 10 | The following test is about 100 Goroutines writing and 100 Groutines reading. The test is executed on Macbook (macOS 10.13.2, 2 core (2.3G Intel Core i5), 8G LPDDR3) 11 | 12 | ![image](https://github.com/easierway/concurrent_map/blob/master/map_benchmark.png) 13 | 14 | ### FAQ 15 | 1 Why not provide the default hash function for partition? 16 | 17 | Ans: As you known, the partition solution would impact the performance significantly. The proper partition solution balances the access to the different partitions and avoid of the hot partition. The access mode highly relates to your business. So, the better partition solution would just be designed according to your business. 18 | -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/concurrent_map.go: -------------------------------------------------------------------------------- 1 | package concurrent_map 2 | 3 | import ( 4 | "sync" 5 | ) 6 | 7 | // ConcurrentMap is a thread safe map collection with better performance. 8 | // The backend map entries are separated into the different partitions. 9 | // Threads can access the different partitions safely without lock. 10 | type ConcurrentMap struct { 11 | partitions []*innerMap 12 | numOfBlockets int 13 | } 14 | 15 | // Partitionable is the interface which should be implemented by key type. 16 | // It is to define how to partition the entries. 17 | type Partitionable interface { 18 | // Value is raw value of the key 19 | Value() interface{} 20 | 21 | // PartitionKey is used for getting the partition to store the entry with the key. 22 | // E.g. the key's hash could be used as its PartitionKey 23 | // The partition for the key is partitions[(PartitionKey % m.numOfBlockets)] 24 | // 25 | // 1 Why not provide the default hash function for partition? 26 | // Ans: As you known, the partition solution would impact the performance significantly. 27 | // The proper partition solution balances the access to the different partitions and 28 | // avoid of the hot partition. The access mode highly relates to your business. 29 | // So, the better partition solution would just be designed according to your business. 30 | PartitionKey() int64 31 | } 32 | 33 | type innerMap struct { 34 | m map[interface{}]interface{} 35 | lock sync.RWMutex 36 | } 37 | 38 | func createInnerMap() *innerMap { 39 | return &innerMap{ 40 | m: make(map[interface{}]interface{}), 41 | } 42 | } 43 | 44 | func (im *innerMap) get(key Partitionable) (interface{}, bool) { 45 | keyVal := key.Value() 46 | im.lock.RLock() 47 | v, ok := im.m[keyVal] 48 | im.lock.RUnlock() 49 | return v, ok 50 | } 51 | 52 | func (im *innerMap) set(key Partitionable, v interface{}) { 53 | keyVal := key.Value() 54 | im.lock.Lock() 55 | im.m[keyVal] = v 56 | im.lock.Unlock() 57 | } 58 | 59 | func (im *innerMap) del(key Partitionable) { 60 | keyVal := key.Value() 61 | im.lock.Lock() 62 | delete(im.m, keyVal) 63 | im.lock.Unlock() 64 | } 65 | 66 | // CreateConcurrentMap is to create a ConcurrentMap with the setting number of the partitions 67 | func CreateConcurrentMap(numOfPartitions int) *ConcurrentMap { 68 | var partitions []*innerMap 69 | for i := 0; i < numOfPartitions; i++ { 70 | partitions = append(partitions, createInnerMap()) 71 | } 72 | return &ConcurrentMap{partitions, numOfPartitions} 73 | } 74 | 75 | func (m *ConcurrentMap) getPartition(key Partitionable) *innerMap { 76 | partitionID := key.PartitionKey() % int64(m.numOfBlockets) 77 | return (*innerMap)(m.partitions[partitionID]) 78 | } 79 | 80 | // Get is to get the value by the key 81 | func (m *ConcurrentMap) Get(key Partitionable) (interface{}, bool) { 82 | return m.getPartition(key).get(key) 83 | } 84 | 85 | // Set is to store the KV entry to the map 86 | func (m *ConcurrentMap) Set(key Partitionable, v interface{}) { 87 | im := m.getPartition(key) 88 | im.set(key, v) 89 | } 90 | 91 | // Del is to delete the entries by the key 92 | func (m *ConcurrentMap) Del(key Partitionable) { 93 | im := m.getPartition(key) 94 | im.del(key) 95 | } 96 | -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/concurrent_map_benchmark_adapter.go: -------------------------------------------------------------------------------- 1 | package concurrent_map 2 | 3 | type ConcurrentMapBenchmarkAdapter struct { 4 | cm *ConcurrentMap 5 | } 6 | 7 | func (m *ConcurrentMapBenchmarkAdapter) Set(key interface{}, value interface{}) { 8 | m.cm.Set(StrKey(key.(string)), value) 9 | } 10 | 11 | func (m *ConcurrentMapBenchmarkAdapter) Get(key interface{}) (interface{}, bool) { 12 | return m.cm.Get(StrKey(key.(string))) 13 | } 14 | 15 | func (m *ConcurrentMapBenchmarkAdapter) Del(key interface{}) { 16 | m.cm.Del(StrKey(key.(string))) 17 | } 18 | 19 | func CreateConcurrentMapBenchmarkAdapter(numOfPartitions int) *ConcurrentMapBenchmarkAdapter { 20 | conMap := CreateConcurrentMap(numOfPartitions) 21 | return &ConcurrentMapBenchmarkAdapter{conMap} 22 | } 23 | -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/concurrent_map_test.go: -------------------------------------------------------------------------------- 1 | package concurrent_map 2 | 3 | import ( 4 | "math/rand" 5 | "strconv" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | func TestBasicOPs(t *testing.T) { 11 | for i := 0; i < 10; i++ { 12 | testV := rand.Intn(1000) 13 | m := CreateConcurrentMap(99) 14 | v, ok := m.Get(StrKey("Hello")) 15 | if v != nil || ok != false { 16 | t.Error("init/get failed") 17 | } 18 | m.Set(StrKey("Hello"), testV) 19 | v, ok = m.Get(StrKey("Hello")) 20 | if v.(int) != testV || ok != true { 21 | t.Error("set/get failed.") 22 | } 23 | m.Del(StrKey("Hello")) 24 | v, ok = m.Get(StrKey("Hello")) 25 | if v != nil || ok != false { 26 | t.Error("del failed") 27 | } 28 | } 29 | } 30 | 31 | func TestInt64KeyBasicOPs(t *testing.T) { 32 | for i := 0; i < 10; i++ { 33 | testV := rand.Int63n(1024) 34 | cm := CreateConcurrentMap(99) 35 | var key int64 = 1023 36 | v, ok := cm.Get(I64Key(key)) 37 | if v != nil || ok != false { 38 | t.Error("init/get failed") 39 | } 40 | cm.Set(I64Key(key), testV) 41 | v, ok = cm.Get(I64Key(key)) 42 | if v.(int64) != testV || ok != true { 43 | t.Error("set/get failed.") 44 | } 45 | cm.Del(I64Key(key)) 46 | v, ok = cm.Get(I64Key(key)) 47 | if v != nil || ok != false { 48 | t.Error("del failed") 49 | } 50 | } 51 | } 52 | 53 | func TestInCurrentEnv(t *testing.T) { 54 | m := CreateConcurrentMap(99) 55 | go func() { 56 | 57 | for i := 0; i < 100; i++ { 58 | if v, ok := m.Get(StrKey(strconv.Itoa(i))); ok { 59 | if v != i*i { 60 | t.Error("Fail") 61 | } 62 | } else { 63 | if v != nil { 64 | t.Error("Fail") 65 | } 66 | } 67 | 68 | } 69 | 70 | }() 71 | go func() { 72 | for i := 0; i < 100; i++ { 73 | m.Set(StrKey(strconv.Itoa(i)), i*i) 74 | } 75 | 76 | }() 77 | time.Sleep(time.Second * 1) 78 | } 79 | -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/int64_key.go: -------------------------------------------------------------------------------- 1 | package concurrent_map 2 | 3 | type Int64Key struct { 4 | value int64 5 | } 6 | 7 | // PartitionID is created by string's hash 8 | func (i *Int64Key) PartitionKey() int64 { 9 | return i.value 10 | } 11 | 12 | // Value is the raw string 13 | func (i *Int64Key) Value() interface{} { 14 | return i.value 15 | } 16 | 17 | // StrKey is to convert a string to StringKey 18 | func I64Key(key int64) *Int64Key { 19 | return &Int64Key{key} 20 | } 21 | -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/map_benchmark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/java-aodeng/golang-examples/b3f7e5a9cbdbbeff4e298cb4421c0a60ecfb012d/src/go-19/module_package/vendor/github.com/easierway/concurrent_map/map_benchmark.png -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/map_benchmark_test.go: -------------------------------------------------------------------------------- 1 | package concurrent_map 2 | 3 | import ( 4 | "strconv" 5 | "sync" 6 | "testing" 7 | ) 8 | 9 | type Map interface { 10 | Set(key interface{}, val interface{}) 11 | Get(key interface{}) (interface{}, bool) 12 | Del(key interface{}) 13 | } 14 | 15 | func benchmarkMap(b *testing.B, hm Map) { 16 | for i := 0; i < b.N; i++ { 17 | var wg sync.WaitGroup 18 | for i := 0; i < 100; i++ { 19 | wg.Add(1) 20 | go func() { 21 | for i := 0; i < 100000; i++ { 22 | hm.Set(strconv.Itoa(i), i*i) 23 | hm.Set(strconv.Itoa(i), i*i) 24 | hm.Del(strconv.Itoa(i)) 25 | } 26 | wg.Done() 27 | }() 28 | } 29 | for i := 0; i < 100; i++ { 30 | wg.Add(1) 31 | go func() { 32 | for i := 0; i < 100000; i++ { 33 | hm.Get(strconv.Itoa(i)) 34 | } 35 | wg.Done() 36 | }() 37 | } 38 | wg.Wait() 39 | } 40 | } 41 | 42 | func BenchmarkSyncmap(b *testing.B) { 43 | b.Run("map with RWLock", func(b *testing.B) { 44 | hm := CreateRWLockMap() 45 | benchmarkMap(b, hm) 46 | }) 47 | 48 | b.Run("sync.map", func(b *testing.B) { 49 | hm := CreateSyncMapBenchmarkAdapter() 50 | benchmarkMap(b, hm) 51 | }) 52 | 53 | b.Run("concurrent map", func(b *testing.B) { 54 | superman := CreateConcurrentMapBenchmarkAdapter(199) 55 | benchmarkMap(b, superman) 56 | }) 57 | } 58 | -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/rwlock_map_benchmark_adapter.go: -------------------------------------------------------------------------------- 1 | package concurrent_map 2 | 3 | import "sync" 4 | 5 | type RWLockMap struct { 6 | m map[interface{}]interface{} 7 | lock sync.RWMutex 8 | } 9 | 10 | func (m *RWLockMap) Get(key interface{}) (interface{}, bool) { 11 | m.lock.RLock() 12 | v, ok := m.m[key] 13 | m.lock.RUnlock() 14 | return v, ok 15 | } 16 | 17 | func (m *RWLockMap) Set(key interface{}, value interface{}) { 18 | m.lock.Lock() 19 | m.m[key] = value 20 | m.lock.Unlock() 21 | } 22 | 23 | func (m *RWLockMap) Del(key interface{}) { 24 | m.lock.Lock() 25 | delete(m.m, key) 26 | m.lock.Unlock() 27 | } 28 | 29 | func CreateRWLockMap() *RWLockMap { 30 | m := make(map[interface{}]interface{}, 0) 31 | return &RWLockMap{m: m} 32 | } 33 | -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/string_key.go: -------------------------------------------------------------------------------- 1 | package concurrent_map 2 | 3 | import "unsafe" 4 | 5 | // StringKey is for the string type key 6 | type StringKey struct { 7 | value string 8 | } 9 | 10 | const ( 11 | c1_32 uint32 = 0xcc9e2d51 12 | c2_32 uint32 = 0x1b873593 13 | ) 14 | 15 | func hash(str string) uint32 { 16 | data := ([]byte)(str) 17 | var h1 uint32 = 37 18 | 19 | nblocks := len(data) / 4 20 | var p uintptr 21 | if len(data) > 0 { 22 | p = uintptr(unsafe.Pointer(&data[0])) 23 | } 24 | 25 | p1 := p + uintptr(4*nblocks) 26 | for ; p < p1; p += 4 { 27 | k1 := *(*uint32)(unsafe.Pointer(p)) 28 | k1 *= c1_32 29 | k1 = (k1 << 15) | (k1 >> 17) // rotl32(k1, 15) 30 | k1 *= c2_32 31 | 32 | h1 ^= k1 33 | h1 = (h1 << 13) | (h1 >> 19) // rotl32(h1, 13) 34 | h1 = h1*5 + 0xe6546b64 35 | } 36 | 37 | tail := data[nblocks*4:] 38 | 39 | var k1 uint32 40 | switch len(tail) & 3 { 41 | case 3: 42 | k1 ^= uint32(tail[2]) << 16 43 | fallthrough 44 | case 2: 45 | k1 ^= uint32(tail[1]) << 8 46 | fallthrough 47 | case 1: 48 | k1 ^= uint32(tail[0]) 49 | k1 *= c1_32 50 | k1 = (k1 << 15) | (k1 >> 17) // rotl32(k1, 15) 51 | k1 *= c2_32 52 | h1 ^= k1 53 | } 54 | 55 | h1 ^= uint32(len(data)) 56 | 57 | h1 ^= h1 >> 16 58 | h1 *= 0x85ebca6b 59 | h1 ^= h1 >> 13 60 | h1 *= 0xc2b2ae35 61 | h1 ^= h1 >> 16 62 | 63 | return (h1 << 24) | (((h1 >> 8) << 16) & 0xFF0000) | (((h1 >> 16) << 8) & 0xFF00) | (h1 >> 24) 64 | } 65 | 66 | // PartitionID is created by string's hash 67 | func (s *StringKey) PartitionKey() int64 { 68 | return int64(hash(s.value)) 69 | } 70 | 71 | // Value is the raw string 72 | func (s *StringKey) Value() interface{} { 73 | return s.value 74 | } 75 | 76 | // StrKey is to convert a string to StringKey 77 | func StrKey(key string) *StringKey { 78 | return &StringKey{key} 79 | } 80 | -------------------------------------------------------------------------------- /src/go-19/module_package/vendor/github.com/easierway/concurrent_map/sync_map_benchmark_adapter.go: -------------------------------------------------------------------------------- 1 | package concurrent_map 2 | 3 | import "sync" 4 | 5 | func CreateSyncMapBenchmarkAdapter() *SyncMapBenchmarkAdapter { 6 | return &SyncMapBenchmarkAdapter{} 7 | } 8 | 9 | type SyncMapBenchmarkAdapter struct { 10 | m sync.Map 11 | } 12 | 13 | func (m *SyncMapBenchmarkAdapter) Set(key interface{}, val interface{}) { 14 | m.m.Store(key, val) 15 | } 16 | 17 | func (m *SyncMapBenchmarkAdapter) Get(key interface{}) (interface{}, bool) { 18 | return m.m.Load(key) 19 | } 20 | 21 | func (m *SyncMapBenchmarkAdapter) Del(key interface{}) { 22 | m.m.Delete(key) 23 | } 24 | -------------------------------------------------------------------------------- /src/go-38/filter.go: -------------------------------------------------------------------------------- 1 | package go_38 2 | 3 | // Request 入参定义 4 | type Request interface{} 5 | 6 | // Response 响应参数定义 7 | type Response interface{} 8 | 9 | // Filter interface is the definition of the data processing components 10 | // Pipe-Filter structure 11 | type Filter interface { 12 | Process(data Request) (Response, error) 13 | } 14 | -------------------------------------------------------------------------------- /src/go-38/pipe_filter_test.go: -------------------------------------------------------------------------------- 1 | package go_38 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | /* 10 | pipe-filter模式 11 | - 非常适合与数据处理及数据分析系统 12 | - Filter封装数据处理的能力 13 | - 松耦合:Filter只跟数据(格式)耦合 14 | - Pipe用于连接Filter传递数据或者在异步处理过程中缓冲数据流进程内同步调用时,pipe演变为数据在方法调用传递 15 | 16 | */ 17 | 18 | func TestStringSplit(t *testing.T) { 19 | //定义分隔符号 20 | sf := NewSplitFilter(",") 21 | //定义参数 22 | resp, err := sf.Process("1,2,3") 23 | if err != nil { 24 | t.Fatal(err) 25 | } 26 | parts, ok := resp.([]string) 27 | if !ok { 28 | t.Fatalf("Repsonse type is %T, but the expected type is string", parts) 29 | } 30 | if !reflect.DeepEqual(parts, []string{"1", "2", "3"}) { 31 | t.Errorf("Expected value is {\"1\",\"2\",\"3\"}, but actual is %v", parts) 32 | } 33 | t.Error(parts) 34 | } 35 | 36 | /*参数是string类型,处理了 37 | === RUN TestStringSplit 38 | pipe_filter_test.go:32: [1 2 3] 39 | --- FAIL: TestStringSplit (0.00s) 40 | 41 | FAIL 42 | */ 43 | 44 | func TestWrongInput(t *testing.T) { 45 | sf := NewSplitFilter(",") 46 | a, err := sf.Process(123) 47 | if err == nil { 48 | t.Fatal("An error is expected.") 49 | } 50 | fmt.Println(a) 51 | } 52 | 53 | /*运行结果,参数不是string类型,不会处理 54 | === RUN TestWrongInput 55 | 56 | --- PASS: TestWrongInput (0.00s) 57 | PASS 58 | */ 59 | -------------------------------------------------------------------------------- /src/go-38/split_filter.go: -------------------------------------------------------------------------------- 1 | package go_38 2 | 3 | import ( 4 | "errors" 5 | "strings" 6 | ) 7 | 8 | // SplitFilterWrongFormatError 定义异常信息 9 | var SplitFilterWrongFormatError = errors.New("input data should be string") 10 | 11 | // SplitFilter 定义分割符号 12 | type SplitFilter struct { 13 | delimiter string 14 | } 15 | 16 | func NewSplitFilter(delimiter string) *SplitFilter { 17 | return &SplitFilter{delimiter} 18 | } 19 | 20 | func (sf *SplitFilter) Process(data Request) (Response, error) { 21 | str, ok := data.(string) //检查数据格式/类型,是否可以处理 22 | if !ok { 23 | return nil, SplitFilterWrongFormatError 24 | } 25 | //按照分割符号分割传入的参数 26 | parts := strings.Split(str, sf.delimiter) 27 | return parts, nil 28 | } 29 | -------------------------------------------------------------------------------- /src/series/my_series.go: -------------------------------------------------------------------------------- 1 | package series 2 | 3 | //自定义的包 4 | 5 | //首字母小写的函数外部不能调用 6 | func square(n int) int { 7 | return n * n 8 | } 9 | 10 | func Square(n int) int { 11 | return n * n 12 | } 13 | --------------------------------------------------------------------------------