search
HomeBackend DevelopmentGolangSlice returns unexpected length

Slice returns unexpected length

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!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Logging Errors Effectively in Go ApplicationsLogging Errors Effectively in Go ApplicationsApr 30, 2025 am 12:23 AM

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.

Empty Interfaces ( interface{} ) in Go: Use Cases and ConsiderationsEmpty Interfaces ( interface{} ) in Go: Use Cases and ConsiderationsApr 30, 2025 am 12:23 AM

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

Comparing Concurrency Models: Go vs. Other LanguagesComparing Concurrency Models: Go vs. Other LanguagesApr 30, 2025 am 12:20 AM

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

Go's Concurrency Model: Goroutines and Channels ExplainedGo's Concurrency Model: Goroutines and Channels ExplainedApr 30, 2025 am 12:04 AM

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

Interfaces and Polymorphism in Go: Achieving Code ReusabilityInterfaces and Polymorphism in Go: Achieving Code ReusabilityApr 29, 2025 am 12:31 AM

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

What is the role of the 'init' function in Go?What is the role of the 'init' function in Go?Apr 29, 2025 am 12:28 AM

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

Interface Composition in Go: Building Complex AbstractionsInterface Composition in Go: Building Complex AbstractionsApr 29, 2025 am 12:24 AM

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.

Potential Pitfalls and Considerations When Using init Functions in GoPotential Pitfalls and Considerations When Using init Functions in GoApr 29, 2025 am 12:02 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

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.