Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore B28724

B28724

Published by kophakan2213, 2020-10-13 07:07:46

Description: B28724

Search

Read the Text Version

336 Appendix Solutions } for y := range grid.cells { grid.cells[y] = make([]cell, size.X) for x := range grid.cells[y] { cell := &grid.cells[y][x] cell.groundData.LifeSigns = rand.Intn(1000) } } return grid } // Size returns a Point representing the size of the grid. func (g *MarsGrid) Size() image.Point { return g.bounds.Max } // Occupy occupies a cell at the given point in the grid. It // returns nil if the point is already occupied or the point is outside // the grid. Otherwise it returns a value that can be used // to move to different places on the grid. func (g *MarsGrid) Occupy(p image.Point) *Occupier { g.mu.Lock() defer g.mu.Unlock() cell := g.cell(p) if cell == nil || cell.occupier != nil { return nil } cell.occupier = &Occupier{ grid: g, pos: p, } return cell.occupier } func (g *MarsGrid) cell(p image.Point) *cell { if !p.In(g.bounds) { return nil } return &g.cells[p.Y][p.X]

Unit 7 337 } // Occupier represents an occupied cell in the grid. type Occupier struct { grid *MarsGrid pos image.Point } // MoveTo moves the occupier to a different cell in the grid. // It reports whether the move was successful // It might fail because it was trying to move outside // the grid or because the cell it's trying to move into // is occupied. If it fails, the occupier remains in the same place. func (o *Occupier) MoveTo(p image.Point) bool { o.grid.mu.Lock() defer o.grid.mu.Unlock() newCell := o.grid.cell(p) if newCell == nil || newCell.occupier != nil { return false } o.grid.cell(o.pos).occupier = nil newCell.occupier = o o.pos = p return true } // Sense returns sensory data from the current cell. func (o *Occupier) Sense() SensorData { o.grid.mu.Lock() defer o.grid.mu.Unlock() return o.grid.cell(o.pos).groundData } // Pos returns the current grid position of the occupier. func (o *Occupier) Pos() image.Point { return o.pos }



INDEX Symbols maps vs. 149 mutating 214 _ (blank identifier) 77, 125 out-of-range elements 123 ! (not operator) 29–30 pointing to 209–210 ' ' (runes) 70–71 pointing to with slices 215–216 [ ] (square brackets) 122, 147 slicing 131–133 { } (curly braces) 8–9, 27, 124 assignment operator 19–20, 27 * (dereference operator) 202–203 associative arrays 146 * (pointers) 204 Atoi function 85 & (address operator) 202–203, 208 && operator 29 B % (modulus operator) 14, 28, 89 %b format verb (binary) 58 backticks (` `) 69–70 %c format verb (character) 71 big numbers %f format verb (floating-point) 48–49 %T format verb (type) 55 big package 64 %v format verb (value) 15–16, 165, 227 big.Int type 64 %x format verb (hexadecimal) 57 constants 66 ` ` (raw string literals) 69–70 blank identifier (_) 77, 125 + (plus sign) 14, 80 boilerplate 181 <- channel operator 258, 267 Boolean values 24–26, 29, 31–33 converting 86 A branching with if statement 26–27 address operator (&) 202–203, 208 with switch statement 30–31 After function 260, 275 bytes 70–72 ambiguous selector 183 anonymous functions (function literals) 112, C 115 call stack 245 APIs (Application Programming capacity of slices 140 Interfaces) 167 append function and 141–142 append function 138–139, 141–142 Cascading Style Sheets. See CSS arguments 15, 95 case keyword 30, 40 arrays channels accessing elements of 122–123 <- operator 258, 267 arrays of arrays 128 general discussion 257–259 copying 126–127 select statement 260–262 declaring 122, 124 characters 68 iterating through 125–126 manipulating with Caesar cipher 73–74 339

340 Index characters (continued) E manipulating with ROT13 74–75 overview 70–72 ellipsis (...) 97, 144 embedding 177 ciphering text 90 empty interface{} 97 closures 112–115 equality operator 27 cloud computing 3 Error() method 241 code duplication 39 errors code points 70–72 code smell 39 creating new error values 238–244 coerce types 80 and type assertions 243–244 communicating sequential processes. See CSP distinguishing between errors 240–241 comparison operators 25 multiple errors 242–243 composite literals file writing errors 233–235 for arrays 124 and defer keyword 235–236 for maps 147 graceful error handling 236–238 for slices 133–134 for structures 164–165 handling 231–238 composition, composing structures with panic mechanism 244–246 178–180 exceptions in other languages 245 concurrency 253–254 recover 246 concurrent state errors package 173, 238 New constructor 241 long-lived tasks 274–280 escape sequences 69 mutexes 270–274 event loops 275 constants const keyword 17–18, 21, 66 F large numbers 66 constructor functions 172–173, 249 fallthrough keyword 30 Contains function 96 false constant 24–25 CSP (communicating sequential Fields function 268 file.Close() method 235 processes) 220 file.IsDir() function 232 CSS (Cascading Style Sheets) 56–57 floating-point numbers 45, 49 curly braces ({ }) 8–9, 27, 124 accuracy of 49 D converting 82 declaring 46 dangling pointers 202 deadlocks 262–263, 274 float32 type (single precision) 47 decimal degrees 162 zero value 47 DecodeRuneInString function 76 displaying 48–49 default keyword 30 fmt (format) package 7, 41, 156, 193 defer keyword 235–236, 272 Print function 15 delegation 184 Printf function 15–16, 57 delete function 149 Println function 1, 15, 97 dereference operator (*) 202–203 Sprintf function 84 dictionaries (maps) 146 for loop dot notation 106, 162 for keyword 31 double precision floating-point numbers 47 range keyword 76, 89, 125, 128, 137, 151 duplicated code 39 format verbs 16, 48, 55–57, 71, 165, 227 dynamic typing 85 forwarding methods 181–183 functions anonymous 112–115 assigning to variables 109–110 declaring 7, 94–97

Index 341 functions (continued) interfaces declaring function types 112 discovering later 190–192 func keyword 7–8, 94 interface embedding 194 literal 112 interface type 187–190 nil function values 224–225 nil 227–228 passing to other functions 110–111 pointers and 216–218 scope 36, 99 satisfying 193–194 signature 110 interior pointers 213–214 G interpreter 5 Intn function 94, 157 Go Playground io package limitations of 286 overview 6 Reader interface 193 ReadWriter interface 193 Go Proverbs 233 Writer interface 193, 236 golang 6, 89 ioutil package golint tool 46 ReadDir 231 gophers 4 Itoa function 84 goroutines J blocked 262–263 channels JSON (JavaScript Object Notation) customizing with struct tags 168–169 general discussion 257–259 encoding structures to 167–168 select statement 260–262 deadlocked 262–263 L multiple 256–257 pipelines 263–267 leaking resources 233 starting 254–255 len function 74, 122 literal numbers 17 H literal values half-open range 131 bytes 70–72 hashes 146 characters 70–72 hexadecimal 57 manipulating with Caesar cipher 73–75 I manipulating with ROT13 74–75 code points 70–72 if statements 26–27, 37, 89 runes image package 276 decoding strings into 75–77 immutable strings 73 general discussion 70–72 import keyword 7 string variables import path 21 declaring 69–70 increment operator (++) 19–20 decoding strings into runes 75–77 indirection 202 immutable nature of 72–87 inheritance 184 raw string literals 69–70 integers 45, 53 Lock method (mutexes) 271 logical operators 27–29 declaring 54 loops, repetition with 31–33 architecture-independent types 54 displaying types 55 M displaying bits 58 magic numbers 17 int type 55 main function 35, 98, 156, 239, 258 Unix time 60 main package 7 wrapping 58

342 Index make function 145 pointers as parameters 210–211 channels 257–259 with interior pointers 213–214 general discussion 143 mutexes 270–274 preallocating maps with 150 mutual exclusion 271 preallocating slices with 143 N maps arrays vs. 149 name collisions (embedding) 183–184 as pointers 215 new lines 69 declaring 147–148 nibbles 57 grouping data with 151–152 nil keys 146 nil 226–227 guarding against preallocating 150 overview 221–222 repurposing as sets 152–153 with methods 223–224 using to count things 150–151 nil function values 224–225 Marshal function 167 nil interfaces 227–228 MarshalJSON method 195 nil maps 226–227 math calculations nil slices 225–226 nil value 85 assignment operator 19–20 not operator (!) 29 constants 17–18 numeric types, converting 81–82 increment operator (++) 19–20 performing 14–15 O pseudorandom number generation 20–21 variables object composition 177 overflow error 67 declaring multiple 18–19 overview 17–18 P math package 7, 41, 83 Abs function 51 package keyword 7 Acos function 174–175 packages Cos function 7–8, 174–175 MaxInt16 constant 82–83 declaring 7 MaxUint16 constant 58–60 documentation 94–97 MaxUint8 constant 82–83 panic mechanism 244–246 MinInt16 constant 82–83 exceptions in other languages 245 Pi constant 47, 174–175 passing arguments to 245–246 Sin function 7–8 recover function 246 Sincos function 174–175 parameters Sqrt function 7–8 overview 95 Tan function 7–8 pointers as 210–211 Trunc function 151–152 pipelines 263–267 memory address 202 plus operator (+) 80 methods 64 pointers (*) 72, 202–204 adding behavior to types with 105–107 address operator (&) 202–203 attaching to slices 136–137 declaring 203–205 attaching to structures 171–172 dereference operator (*) 202–203 forwarding 181–183 enabling mutation 210–215 guarding against nil values with 223–224 types as alternative to classes 174–175 interior pointers 213–214 modulus operator (%) 14, 89 mutating arrays 214–215 mutations 210–215 pointer receivers 211–213 mutating arrays 214–215 pointers as parameters 210–211 pointer receivers 211–213

Index 343 pointers (*) (continued) sets interfaces and 216–218 repurposing maps as 152–153 maps as 215 set membership 152 overusing 218 pointer arithmetic 203 shared values 269 pointer receivers 211–213 short declaration 36 pointing to arrays 209–210 side effect free functions 99 pointing to structures 208–209 signed integer types 54 slices point at arrays 215–216 single precision floating-point numbers 47 single quotes (' ') 71 polymorphism 188 Sleep function 158, 254 precision 48 slices Print function 15 Printf function 15–16, 55 appending elements to 139, 141–142, 145 Println function 8, 15, 97 attaching methods 136–137 pseudorandom numbers 20–21 capacity of 140 composite literals for 133–134 R declaring variadic functions 144 grouping data with 151–152 race condition 270 length of 140 RAM (random access memory) 34, 201 nil 225–226 rand package 21, 41, 95 pointing to arrays 215–216 preallocating 143 Intn function 94, 156 slicing arrays 131–133 random numbers 20 three-index slicing 142–143 Seed function 156 with structures 166–167 range keyword 76, 89, 125, 129, 137, 151, 246, snake_case 168 sort package 136 266 Float64s function 152–153 raw string literals 69–70 Slice function 224–225 ReadDir function 231 Sort method 136 ReadWriter interface 194 Strings function 136 receiver (methods) 106 StringSlice type 136 recover function (panic) 246 Sprintf function 86 refactoring 39, 235 square brackets ([ ]) 122, 147 REMS (Rover Environmental Monitoring static typing 85 strconv (string conversion) package 84 Station) 93, 108, 177 Atoi function 85, 96 Repeat function 89 Itoa function 84 return keyword 99 String method 193 ROT13 cipher 74–75 string variables rounding errors 49 converting 84–85 Rover Environmental Monitoring Station. declaring 69–70 decoding strings into runes 75–77 See REMS immutable nature of 72–87 runes raw string literals 69–70 Stringer interface 197 decoding strings into 75–77 strings package 268 general discussion 70–72 Contains function 24–25, 95, 263 Fields function 153, 267–268 S Join function 134–135, 238–239 Repeat function 89 Seed method 156 Replace function 88–90 select statement 260, 275–276 ToUpper function 88, 90, 187–190, 216–217 TrimSpace function 134–135 channels and 260–262 semicolons (;) 9 sentinel value 263

344 Index structures U as alternative to classes 174–175 attaching methods to 171–172 uint type 55 composing with composition 178–180 uint16 type 56 copying 165–166 uint64 type 56 customizing JSON with struct tags 168–169 declaring 162–163 and constants 66 encoding to JSON 167–168 uint8 type 56, 71 initializing with composite literals 164–165 Unix function (time) 60, 95 pointing to 208–209 Unlock method (mutexes) 271 reusing with types 163–164 unsigned integer types 54 struct embedding 181 untyped constants 66, 102 struct tags 168–169 url package 242 with slices 166–167 Error type 247 switch statement 30, 37 Parse method 247 sync package, Mutex type 272 syntax errors 10 V T validating parameters 238 var keyword 17–18 three-index slicing 142–143 variable scope threequals operator 26 time package 158 narrow vs. wide scope 38 overview 35–49 After function 260, 275 short declaration 36 Date function 190–192 variables 17–18 Duration function 260–261 assigning functions to 109–110 Hour constant 211–212 declaring multiple 18–19 Millisecond constant 260–261, 274–280 floating-point 46 Now function 211–213 Second constant 31–32, 110–111, 254, displaying 48–49 single precision 47 256–257, 260, 274 zero value 47 Sleep function 31, 110, 158, 254, 256–257, integer 54 architecture-independent types 54 260, 270, 274 displaying types 55 Unix function 60, 95 string UTC constant 190 declaring 69–70 time sharing 256 decoding strings into runes 75–77 Time type 212 immutable nature of 72–87 ToUpper function 90 raw string literals 69–70 true constant 24–25 variadic functions, declaring 144 type assertions 243–244 type behavior, adding with methods 105–107 W type conversion Boolean values 86 worker functions 277 caution regarding 82 wrapping (integers) 58 mismatched types 80–81 Writer interface 193 numeric types 81–82 strings 84–85, 87 Z type declaration declaring new types 102–103 zero value 47, 69 using types 104–105 type keyword 102


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook