php editor Youzi often encounters the problem of returning unexpected lengths when using slicing operations. Slicing operation is one of the commonly used array operations. You can obtain some elements of the array by specifying the starting position and ending position. However, sometimes we find that the returned slice length is not as expected, which may be due to some common mistakes or misunderstandings. In this article, we will introduce in detail the problems you may encounter during slicing operations and provide solutions to help you better understand and use slicing operations.
Question content
I was working on golang and I stopped and it confused me.
package main import "fmt" func main() { month := [...]string{1: "jan", 2: "fab", 3: "march", 4: "april", 5: "may", 6: "june", 7: "july", 8: "aug", 9: "sep", 10: "oct", 11: "nov", 12: "dec"} fmt.println(cap(month)) summer := month[6:9] q2 := month[4:7] fmt.println(cap(q2)) fmt.println(len(q2)) fmt.println(cap(summer)) fmt.println(len(summer)) }
The output is
13 9 3 7 3
The month slice has 12 elements, but cap(month)
and len(month)
return 13
, why?
Solution
First, month
is an array - not a slice - whose type is [13]string
. Just looking at its type, we know that it has 13 elements (length) and the slice is of type []string
.
Array and slice indexes start from zero, not from one. Since you did not specify a string
value for the array at index 0
:
month := [...]string{1: "jan", 2: "fab", 3: "march", 4: "april", 5: "may", 6: "june", 7: "july", 8: "aug", 9: "sep", 10: "oct", 11: "nov", 12: "dec"}
It is equivalent to:
month := [13]string{0: "", 1: "jan", 2: "fab", 3: "march", 4: "april", 5: "may", 6: "june", 7: "july", 8: "aug", 9: "sep", 10: "oct", 11: "nov", 12: "dec"}
That is, the zero value
(i.e. the empty string) of string is provided as the first element.
Please note that I have replaced ...
with 13
. The ellipsis tells the compiler to infer the length of the array (which is part of its type) based on the initializer.
Even if you use a slice literal instead of an array literal as an initializer:
month := []string{1: "Jan", 2: "Fab", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"}
For the same reasons as above, the length of (in this case the slice) month
will still be 13
.
The above is the detailed content of Slice returns unexpected length. For more information, please follow other related articles on the PHP Chinese website!

Effective Go application error logging requires balancing details and performance. 1) Using standard log packages is simple but lacks context. 2) logrus provides structured logs and custom fields. 3) Zap combines performance and structured logs, but requires more settings. A complete error logging system should include error enrichment, log level, centralized logging, performance considerations, and error handling modes.

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

Go'sconcurrencymodelisuniqueduetoitsuseofgoroutinesandchannels,offeringalightweightandefficientapproachcomparedtothread-basedmodelsinlanguageslikeJava,Python,andRust.1)Go'sgoroutinesaremanagedbytheruntime,allowingthousandstorunconcurrentlywithminimal

Go'sconcurrencymodelusesgoroutinesandchannelstomanageconcurrentprogrammingeffectively.1)Goroutinesarelightweightthreadsthatalloweasyparallelizationoftasks,enhancingperformance.2)Channelsfacilitatesafedataexchangebetweengoroutines,crucialforsynchroniz

InterfacesandpolymorphisminGoenhancecodereusabilityandmaintainability.1)Defineinterfacesattherightabstractionlevel.2)Useinterfacesfordependencyinjection.3)Profilecodetomanageperformanceimpacts.

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

Interface combinations build complex abstractions in Go programming by breaking down functions into small, focused interfaces. 1) Define Reader, Writer and Closer interfaces. 2) Create complex types such as File and NetworkStream by combining these interfaces. 3) Use ProcessData function to show how to handle these combined interfaces. This approach enhances code flexibility, testability, and reusability, but care should be taken to avoid excessive fragmentation and combinatorial complexity.

InitfunctionsinGoareautomaticallycalledbeforethemainfunctionandareusefulforsetupbutcomewithchallenges.1)Executionorder:Multipleinitfunctionsrunindefinitionorder,whichcancauseissuesiftheydependoneachother.2)Testing:Initfunctionsmayinterferewithtests,b


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
