课程: Advanced Go Programming: Data Structures, Code Architecture, and Testing
Implementing data structures - Go教程
课程: Advanced Go Programming: Data Structures, Code Architecture, and Testing
Implementing data structures
- [Instructor] Even though Go doesn't offer ready-made data structures like other languages do, we have all the building blocks we need to implement any data structure. Let's take a closer look at how you can achieve this. A stack is a data structure that's related to the linked list. It has a last in, first out element access. New elements are added to the top of the stack and the latest element is read first. They're often used by algorithms because the function call stack exhibits the same behavior. Stacks expose two operations. The Push operation adds a new element to the top of the stack while the Pop operation reads and removes the last element from the top of the stack. Go recently introduced support for generic code, making it possible for us to write code that can be used with multiple data types. We can easily implement a stack by using generic code and a slice. This slice can hold the methods which implement the custom behavior that stacks require. The Push method adds the element on top of the stack, saving it to the slice. The is empty method will check whether the stack contains any entries. The Pop method removes the last element from the slice and returns a pointer to it. When the stack is empty and no elements can be Popped, it returns nil and an error. Let's have a look at the implementation of these methods. The Push method is easily implemented by appending the new element to the slice. This may seem counterintuitive, since we expect the top of the stack to be at index zero, but the append function is the best way to add a new element to a slice. The is empty method simply checks whether the length of the array is zero. The Pop method is slightly more complex, but also easily implemented using the slice available. First, this method uses the is empty method to check whether there are any elements present in the stack. Then we read the last element in the slice, which will be the last appended one, and save it to the top variable. Next, we need to remove this top element from the slice, which we can easily do by passing the end index of the slice to be length minus one. Finally, the function returns a pointer to the top element and a nil error. Now you can see how easy it is to implement custom data structures using Go's structs and slices. You've seen that slices are very flexible and their elements are easily manipulated. This makes them great building blocks and one of the reasons that the Go Standard Library doesn't need to implement a large set of data structures like other languages. You'll practice the same process going forward in the next challenge.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。